From af15582be0fd61cb4d24f697aa14d3a33735c52f Mon Sep 17 00:00:00 2001 From: Jude Kwashie Date: Wed, 11 Nov 2026 11:10:50 +0000 Subject: [PATCH 1/5] fix(messaging,android): skip the background service when no handler is registered A background push started the messaging service even when the app had never registered onBackgroundMessage, and a stored callback handle was never cleared after that registration was removed. Skip the service unless a handler is stored, and honor a manifest flag so an updated app can turn a leftover handler off on installs that are never opened. --- docs/cloud-messaging/receive.md | 19 ++ .../firebase_messaging/CHANGELOG.md | 4 + .../BackgroundHandlerStartDecision.java | 52 +++++ ...erFirebaseMessagingBackgroundExecutor.java | 30 ++- ...lutterFirebaseMessagingBackgroundGate.java | 118 ++++++++++ ...terFirebaseMessagingBackgroundService.java | 9 + .../FlutterFirebaseMessagingReceiver.java | 20 ++ .../BackgroundHandlerStartDecisionTest.java | 70 ++++++ ...erFirebaseMessagingBackgroundGateTest.java | 202 ++++++++++++++++++ 9 files changed, 519 insertions(+), 5 deletions(-) create mode 100644 packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java create mode 100644 packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java create mode 100644 packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecisionTest.java create mode 100644 packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java diff --git a/docs/cloud-messaging/receive.md b/docs/cloud-messaging/receive.md index 7311ec0a428d..4b50f87ab2c8 100644 --- a/docs/cloud-messaging/receive.md +++ b/docs/cloud-messaging/receive.md @@ -186,6 +186,25 @@ A few things to be aware of: 4. If the same flag is set both in the manifest and on the command line, the command line value wins. +##### Turning off the Android background handler {: #android-background-handler-opt-out} + +Registration is stored on the device. Removing `onBackgroundMessage` from `main()` does not +clear it, and a push can start the process without running `main()`. Installs that have not +been opened since the update still start a background Flutter engine. + +To stop that on the next push, add this inside `` in +`android/app/src/main/AndroidManifest.xml`: + +```xml + +``` + +Leave the entry out, or set it to `true`, and a stored handler still runs. `false` takes +effect for a process started by a push, and it wins over a stored handler until the entry +is removed. + #### Web {:#web} {:#web} diff --git a/packages/firebase_messaging/firebase_messaging/CHANGELOG.md b/packages/firebase_messaging/firebase_messaging/CHANGELOG.md index bfdf97ea47d1..ac49b3c0f43c 100644 --- a/packages/firebase_messaging/firebase_messaging/CHANGELOG.md +++ b/packages/firebase_messaging/firebase_messaging/CHANGELOG.md @@ -1,3 +1,7 @@ +## 17.0.2 + + - **FIX**(messaging,android): do not start the background service when no `onBackgroundMessage` handler is registered ([#18940](https://github.com/firebase/flutterfire/issues/18940)). + ## 17.0.1 - **FIX**(android): replace Groovy space-assignment in plugin build.gradle files ([#18837](https://github.com/firebase/flutterfire/issues/18837)). ([09e913ac](https://github.com/firebase/flutterfire/commit/09e913acd98fa25ea6ff547141e7caf421b7b02d)) diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java new file mode 100644 index 000000000000..7309e89f9c18 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java @@ -0,0 +1,52 @@ +// 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; + +/** + * Whether a background message should start the Dart handler. + * + *

{@code manifestEnabled} is null when the app manifest does not set {@code + * firebase_messaging_background_handler_enabled}. + */ +final class BackgroundHandlerStartDecision { + enum Action { + START, + SKIP, + SKIP_AND_CLEAR + } + + private BackgroundHandlerStartDecision() {} + + static Action decide(long callbackHandle, Boolean manifestEnabled) { + if (Boolean.FALSE.equals(manifestEnabled)) { + return Action.SKIP_AND_CLEAR; + } + if (callbackHandle == 0L) { + return Action.SKIP; + } + return Action.START; + } + + /** + * The manifest value for the background handler, or null when the entry is absent or not a + * boolean. Android stores {@code android:value="false"} as a boolean, and sometimes as the string + * {@code "false"}. + */ + static Boolean manifestValue(Object raw) { + if (raw instanceof Boolean) { + return (Boolean) raw; + } + if (raw instanceof String) { + String value = (String) raw; + if ("true".equalsIgnoreCase(value)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(value)) { + return Boolean.FALSE; + } + } + return null; + } +} diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java index f76a3faeb3a5..f6fcb0047a83 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java @@ -36,8 +36,8 @@ */ public class FlutterFirebaseMessagingBackgroundExecutor implements MethodCallHandler { private static final String TAG = "FLTFireBGExecutor"; - private static final String CALLBACK_HANDLE_KEY = "callback_handle"; - private static final String USER_CALLBACK_HANDLE_KEY = "user_callback_handle"; + static final String CALLBACK_HANDLE_KEY = "callback_handle"; + static final String USER_CALLBACK_HANDLE_KEY = "user_callback_handle"; private final AtomicBoolean isCallbackDispatcherReady = new AtomicBoolean(false); @@ -172,6 +172,10 @@ public void startBackgroundIsolate(long callbackHandle) { } boolean isDartBackgroundHandlerRegistered() { + Context context = ContextHolder.getApplicationContext(); + if (context != null && FlutterFirebaseMessagingBackgroundGate.handlerDisabled(context)) { + return false; + } return getPluginCallbackHandle() != 0; } @@ -270,10 +274,26 @@ public static void setUserCallbackHandle(long callbackHandle) { /** Get the registered Dart callback handle for the messaging plugin. Returns 0 if not set. */ private long getPluginCallbackHandle() { + return readPluginCallbackHandle(ContextHolder.getApplicationContext()); + } + + /** Returns the stored plugin callback handle, or 0 when {@code context} is null or unset. */ + static long readPluginCallbackHandle(Context context) { + if (context == null) { + return 0L; + } SharedPreferences prefs = - ContextHolder.getApplicationContext() - .getSharedPreferences(FlutterFirebaseMessagingUtils.SHARED_PREFERENCES_KEY, 0); - return prefs.getLong(CALLBACK_HANDLE_KEY, 0); + context.getSharedPreferences(FlutterFirebaseMessagingUtils.SHARED_PREFERENCES_KEY, 0); + return prefs.getLong(CALLBACK_HANDLE_KEY, 0L); + } + + static void clearCallbackHandles(Context context) { + if (context == null) { + return; + } + SharedPreferences prefs = + context.getSharedPreferences(FlutterFirebaseMessagingUtils.SHARED_PREFERENCES_KEY, 0); + prefs.edit().remove(CALLBACK_HANDLE_KEY).remove(USER_CALLBACK_HANDLE_KEY).apply(); } private void initializeMethodChannel(BinaryMessenger isolate) { diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java new file mode 100644 index 000000000000..8e6c4fa61453 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java @@ -0,0 +1,118 @@ +// 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 android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.util.Log; +import androidx.annotation.Nullable; +import androidx.annotation.VisibleForTesting; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * Reads the stored callback handle and the manifest opt-out, and decides whether this process + * should start the background Dart handler. + */ +final class FlutterFirebaseMessagingBackgroundGate { + static final String METADATA_KEY = "firebase_messaging_background_handler_enabled"; + + private static final String TAG = "FLTFireBGExecutor"; + private static final Object manifestLock = new Object(); + private static final Executor clearExecutor = Executors.newSingleThreadExecutor(); + + private static boolean manifestRead = false; + @Nullable private static Boolean manifestEnabled; + + private FlutterFirebaseMessagingBackgroundGate() {} + + static BackgroundHandlerStartDecision.Action decide(Context context) { + Context appContext = applicationContext(context); + return BackgroundHandlerStartDecision.decide( + FlutterFirebaseMessagingBackgroundExecutor.readPluginCallbackHandle(appContext), + manifestEnabled(appContext)); + } + + /** True when the manifest opts out, including before the stored handles have been deleted. */ + static boolean handlerDisabled(Context context) { + return Boolean.FALSE.equals(manifestEnabled(applicationContext(context))); + } + + static void clearHandles(Context context) { + FlutterFirebaseMessagingBackgroundExecutor.clearCallbackHandles(applicationContext(context)); + } + + /** Preference writes must not run on the main thread. Service startup calls this instead. */ + static void clearHandlesAsync(Context context) { + Context appContext = applicationContext(context); + clearExecutor.execute(() -> clearHandles(appContext)); + } + + @VisibleForTesting + static void awaitClearForTests() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + clearExecutor.execute(latch::countDown); + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("callback handle clear did not finish"); + } + } + + @VisibleForTesting + static void resetForTests() { + synchronized (manifestLock) { + manifestRead = false; + manifestEnabled = null; + } + } + + @Nullable + private static Boolean manifestEnabled(Context context) { + synchronized (manifestLock) { + if (manifestRead) { + return manifestEnabled; + } + } + if (context == null) { + return null; + } + Boolean value = loadManifestEnabled(context); + synchronized (manifestLock) { + if (!manifestRead) { + manifestEnabled = value; + manifestRead = true; + } + return manifestEnabled; + } + } + + @Nullable + private static Boolean loadManifestEnabled(Context context) { + try { + ApplicationInfo info = + context + .getPackageManager() + .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); + if (info.metaData == null || !info.metaData.containsKey(METADATA_KEY)) { + return null; + } + return BackgroundHandlerStartDecision.manifestValue(info.metaData.get(METADATA_KEY)); + } catch (PackageManager.NameNotFoundException exception) { + Log.w(TAG, "Could not read " + METADATA_KEY + " from the manifest.", exception); + return null; + } + } + + @Nullable + private static Context applicationContext(Context context) { + if (context == null) { + return null; + } + Context appContext = context.getApplicationContext(); + return appContext != null ? appContext : context; + } +} diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java index 2586a99b84a8..0f2ffcd11722 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java @@ -78,6 +78,15 @@ public void onCreate() { if (flutterBackgroundExecutor == null) { flutterBackgroundExecutor = new FlutterFirebaseMessagingBackgroundExecutor(); } + BackgroundHandlerStartDecision.Action action = + FlutterFirebaseMessagingBackgroundGate.decide(this); + if (action == BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR) { + // onCreate runs on the main thread, so the preference write happens off it. + FlutterFirebaseMessagingBackgroundGate.clearHandlesAsync(this); + } + if (action != BackgroundHandlerStartDecision.Action.START) { + return; + } flutterBackgroundExecutor.startBackgroundIsolate(); } diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java index a0c4991820e8..e1e5568224ac 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java @@ -15,8 +15,10 @@ import androidx.annotation.VisibleForTesting; import com.google.firebase.messaging.RemoteMessage; import java.util.HashMap; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; public class FlutterFirebaseMessagingReceiver extends BroadcastReceiver { private static final String TAG = "FLTFireMsgReceiver"; @@ -76,6 +78,15 @@ public void onReceive(Context context, Intent intent) { // |-> --------------------- // App in Background/Quit // ------------------------ + BackgroundHandlerStartDecision.Action action = + FlutterFirebaseMessagingBackgroundGate.decide(context); + if (action == BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR) { + FlutterFirebaseMessagingBackgroundGate.clearHandles(context); + } + if (action != BackgroundHandlerStartDecision.Action.START) { + return; + } + Intent onBackgroundMessageIntent = new Intent(context, FlutterFirebaseMessagingBackgroundService.class); @@ -151,4 +162,13 @@ static RemoteMessage remoteMessageFrom(Intent intent) { return new RemoteMessage(extras); } + + @VisibleForTesting + static void awaitBackgroundWorkForTests() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + backgroundExecutor.execute(latch::countDown); + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("background message work did not finish"); + } + } } diff --git a/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecisionTest.java b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecisionTest.java new file mode 100644 index 000000000000..57b1c9209ab5 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecisionTest.java @@ -0,0 +1,70 @@ +// 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.assertNull; + +import org.junit.Test; + +public class BackgroundHandlerStartDecisionTest { + @Test + public void noHandleAndFlagAbsentSkipsWithoutClearing() { + assertEquals( + BackgroundHandlerStartDecision.Action.SKIP, + BackgroundHandlerStartDecision.decide(0L, null)); + } + + @Test + public void storedHandleAndFlagAbsentStarts() { + assertEquals( + BackgroundHandlerStartDecision.Action.START, + BackgroundHandlerStartDecision.decide(42L, null)); + } + + @Test + public void storedHandleAndFlagFalseSkipsAndClears() { + assertEquals( + BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR, + BackgroundHandlerStartDecision.decide(42L, false)); + } + + @Test + public void storedHandleAndFlagTrueStarts() { + assertEquals( + BackgroundHandlerStartDecision.Action.START, + BackgroundHandlerStartDecision.decide(42L, true)); + } + + @Test + public void noHandleAndFlagFalseSkipsAndClears() { + assertEquals( + BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR, + BackgroundHandlerStartDecision.decide(0L, false)); + } + + @Test + public void manifestStringFalseDisables() { + assertEquals(Boolean.FALSE, BackgroundHandlerStartDecision.manifestValue("false")); + assertEquals(Boolean.FALSE, BackgroundHandlerStartDecision.manifestValue("FALSE")); + } + + @Test + public void manifestStringTrueStaysEnabled() { + assertEquals(Boolean.TRUE, BackgroundHandlerStartDecision.manifestValue("true")); + } + + @Test + public void manifestBooleanIsKept() { + assertEquals(Boolean.FALSE, BackgroundHandlerStartDecision.manifestValue(Boolean.FALSE)); + } + + @Test + public void unknownManifestValueIsAbsent() { + assertNull(BackgroundHandlerStartDecision.manifestValue("no")); + assertNull(BackgroundHandlerStartDecision.manifestValue(0)); + assertNull(BackgroundHandlerStartDecision.manifestValue(null)); + } +} diff --git a/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java new file mode 100644 index 000000000000..9be6ad6136ed --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java @@ -0,0 +1,202 @@ +// 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.assertNull; +import static org.junit.Assert.assertTrue; + +import android.app.Application; +import android.app.KeyguardManager; +import android.app.job.JobScheduler; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageInfo; +import android.os.Bundle; +import android.os.Looper; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 28) +public class FlutterFirebaseMessagingBackgroundGateTest { + private Context context; + + @Before + public void setUp() { + context = RuntimeEnvironment.getApplication(); + ContextHolder.setApplicationContext(context); + FlutterFirebaseMessagingBackgroundGate.resetForTests(); + preferences().edit().clear().commit(); + FlutterFirebaseMessagingReceiver.notifications.clear(); + JobIntentService.sClassWorkEnqueuer.clear(); + } + + @After + public void tearDown() { + setManifestValue(null); + FlutterFirebaseMessagingBackgroundGate.resetForTests(); + preferences().edit().clear().commit(); + unlock(); + FlutterFirebaseMessagingReceiver.notifications.clear(); + JobIntentService.sClassWorkEnqueuer.clear(); + ContextHolder.setApplicationContext(null); + } + + @Test + public void backgroundMessageWithoutHandlerDoesNotStartTheService() throws Exception { + lockKeyguard(); + + deliverBackgroundMessage(); + + assertNoBackgroundWorkScheduled(); + } + + @Test + public void backgroundMessageWithStoredHandlerStartsTheService() throws Exception { + lockKeyguard(); + writeHandles(42L, 99L); + + deliverBackgroundMessage(); + + assertTrue(backgroundWorkScheduled()); + assertEquals(42L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.CALLBACK_HANDLE_KEY)); + } + + @Test + public void manifestFalseSkipsAStoredHandlerAndClearsIt() throws Exception { + lockKeyguard(); + writeHandles(42L, 99L); + setManifestValue(Boolean.FALSE); + + deliverBackgroundMessage(); + + assertNoBackgroundWorkScheduled(); + assertEquals(0L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.CALLBACK_HANDLE_KEY)); + assertEquals( + 0L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.USER_CALLBACK_HANDLE_KEY)); + assertFalse( + new FlutterFirebaseMessagingBackgroundExecutor().isDartBackgroundHandlerRegistered()); + } + + @Test + public void manifestStringFalseSkipsAStoredHandler() throws Exception { + lockKeyguard(); + writeHandles(42L, 99L); + setManifestValue("false"); + + deliverBackgroundMessage(); + + assertNoBackgroundWorkScheduled(); + } + + @Test + public void manifestTrueKeepsAStoredHandler() throws Exception { + lockKeyguard(); + writeHandles(42L, 99L); + setManifestValue(Boolean.TRUE); + + deliverBackgroundMessage(); + + assertTrue(backgroundWorkScheduled()); + assertEquals(42L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.CALLBACK_HANDLE_KEY)); + } + + @Test + public void serviceCreateWithManifestFalseDoesNotStartTheIsolate() throws Exception { + writeHandles(42L, 99L); + setManifestValue(Boolean.FALSE); + + Robolectric.buildService(FlutterFirebaseMessagingBackgroundService.class).create(); + Shadows.shadowOf(Looper.getMainLooper()).idle(); + FlutterFirebaseMessagingBackgroundGate.awaitClearForTests(); + + assertEquals(0L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.CALLBACK_HANDLE_KEY)); + assertFalse( + new FlutterFirebaseMessagingBackgroundExecutor().isDartBackgroundHandlerRegistered()); + } + + private void deliverBackgroundMessage() throws InterruptedException { + Intent intent = new Intent("com.google.android.c2dm.intent.RECEIVE"); + Bundle extras = new Bundle(); + extras.putString("google.message_id", "m1"); + intent.putExtras(extras); + new FlutterFirebaseMessagingReceiver().onReceive(context, intent); + FlutterFirebaseMessagingReceiver.awaitBackgroundWorkForTests(); + } + + private void writeHandles(long pluginHandle, long userHandle) { + preferences() + .edit() + .putLong(FlutterFirebaseMessagingBackgroundExecutor.CALLBACK_HANDLE_KEY, pluginHandle) + .putLong(FlutterFirebaseMessagingBackgroundExecutor.USER_CALLBACK_HANDLE_KEY, userHandle) + .commit(); + } + + private long readHandle(String key) { + return preferences().getLong(key, 0L); + } + + private SharedPreferences preferences() { + return context.getSharedPreferences( + FlutterFirebaseMessagingUtils.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE); + } + + private void setManifestValue(Object value) { + PackageInfo info = + Shadows.shadowOf(context.getPackageManager()) + .getInternalMutablePackageInfo(context.getPackageName()); + if (info.applicationInfo.metaData == null) { + info.applicationInfo.metaData = new Bundle(); + } + info.applicationInfo.metaData.remove(FlutterFirebaseMessagingBackgroundGate.METADATA_KEY); + if (value instanceof Boolean) { + info.applicationInfo.metaData.putBoolean( + FlutterFirebaseMessagingBackgroundGate.METADATA_KEY, (Boolean) value); + } else if (value instanceof String) { + info.applicationInfo.metaData.putString( + FlutterFirebaseMessagingBackgroundGate.METADATA_KEY, (String) value); + } + FlutterFirebaseMessagingBackgroundGate.resetForTests(); + } + + private void lockKeyguard() { + KeyguardManager keyguardManager = + (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); + Shadows.shadowOf(keyguardManager).setKeyguardLocked(true); + } + + private void unlock() { + KeyguardManager keyguardManager = + (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); + Shadows.shadowOf(keyguardManager).setKeyguardLocked(false); + } + + private void assertNoBackgroundWorkScheduled() { + assertFalse(backgroundWorkScheduled()); + assertNull( + Shadows.shadowOf((Application) context.getApplicationContext()).getNextStartedService()); + } + + private boolean backgroundWorkScheduled() { + JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + List jobs = scheduler.getAllPendingJobs(); + if (jobs != null && !jobs.isEmpty()) { + return true; + } + return Shadows.shadowOf((Application) context.getApplicationContext()).getNextStartedService() + != null; + } +} From 7d296eccfec999f604ecdaefd0b21ceccf43fabf Mon Sep 17 00:00:00 2001 From: Jude Kwashie Date: Wed, 11 Nov 2026 12:14:09 +0000 Subject: [PATCH 2/5] test(messaging,android): cover the background handler gate on a device The changelog is written at release, and the service test only checked that stored handles were deleted. A background push with no handler, and a second APK with the manifest opt-out, now assert that the service does not start. --- .github/workflows/e2e_tests_messaging.yaml | 20 +++ .github/workflows/reusable_e2e_android.yaml | 37 ++++ docs/cloud-messaging/receive.md | 4 +- .../firebase_messaging/CHANGELOG.md | 4 - ...erFirebaseMessagingBackgroundExecutor.java | 6 + ...terFirebaseMessagingBackgroundService.java | 12 +- ...erFirebaseMessagingBackgroundGateTest.java | 16 ++ .../messaging/example/MainActivity.kt | 163 +++++++++++++++++- .../background_handler_opt_out_test.dart | 51 ++++++ .../example/integration_test/e2e_test.dart | 13 ++ .../remote_notification_delivery.dart | 31 ++++ 11 files changed, 347 insertions(+), 10 deletions(-) create mode 100644 packages/firebase_messaging/firebase_messaging/example/integration_test/background_handler_opt_out_test.dart diff --git a/.github/workflows/e2e_tests_messaging.yaml b/.github/workflows/e2e_tests_messaging.yaml index 6bf8ff469418..f46c8b6960f8 100644 --- a/.github/workflows/e2e_tests_messaging.yaml +++ b/.github/workflows/e2e_tests_messaging.yaml @@ -71,6 +71,26 @@ jobs: TESTS_E2E_FIREBASE_OPTIONS_DART: ${{ secrets.TESTS_E2E_FIREBASE_OPTIONS_DART }} TESTS_E2E_GOOGLE_SERVICES_JSON: ${{ secrets.TESTS_E2E_GOOGLE_SERVICES_JSON }} + # Installs that set the background-handler opt-out must not start the + # service for a stored callback. The flag is manifest meta-data, so this + # job builds a second APK with it set to false. + android-background-handler-disabled: + needs: changes + if: needs.changes.outputs.android == 'true' + uses: ./.github/workflows/reusable_e2e_android.yaml + with: + package-path: 'packages/firebase_messaging/firebase_messaging' + package-scope: 'firebase_messaging*' + test-target: 'integration_test/background_handler_opt_out_test.dart' + android-manifest-metadata: 'firebase_messaging_background_handler_enabled=false' + native-config-args: '--live-tier-plist=messaging' + inject-config-secrets: true + use-firebase-emulators: false + nightly_test_mode: ${{ inputs.nightly_test_mode == true }} + secrets: + TESTS_E2E_FIREBASE_OPTIONS_DART: ${{ secrets.TESTS_E2E_FIREBASE_OPTIONS_DART }} + TESTS_E2E_GOOGLE_SERVICES_JSON: ${{ secrets.TESTS_E2E_GOOGLE_SERVICES_JSON }} + ios: needs: changes if: needs.changes.outputs.ios == 'true' diff --git a/.github/workflows/reusable_e2e_android.yaml b/.github/workflows/reusable_e2e_android.yaml index ae4c8f35fa70..70fc23d80277 100644 --- a/.github/workflows/reusable_e2e_android.yaml +++ b/.github/workflows/reusable_e2e_android.yaml @@ -27,6 +27,13 @@ on: description: 'Integration test entrypoint, relative to the example directory.' type: string default: 'integration_test/e2e_test.dart' + android-manifest-metadata: + description: >- + Space-separated application meta-data entries to set on the example + manifest before the APK is built, as name=true or name=false. Empty + leaves the manifest unchanged. + type: string + default: '' native-config-args: description: >- Arguments for generate-dummy-firebase-configs.dart, e.g. @@ -102,6 +109,7 @@ jobs: PACKAGE_PATH: ${{ inputs.package-path }} TEST_TARGET: ${{ inputs.test-target }} NATIVE_CONFIG_ARGS: ${{ inputs.native-config-args }} + ANDROID_MANIFEST_METADATA: ${{ inputs.android-manifest-metadata }} AVD_ARCH: x86_64 AVD_API_LEVEL: 34 AVD_TARGET: google_apis @@ -193,6 +201,35 @@ jobs: mkdir -p "$HOME/.android" rm -rf "$HOME/.android/avd" ln -s /mnt/avd "$HOME/.android/avd" + - name: Apply Android manifest metadata + if: inputs.android-manifest-metadata != '' + run: | + python3 - <<'PY' + import os, re + from pathlib import Path + raw = os.environ.get("ANDROID_MANIFEST_METADATA", "").strip() + manifest = Path(os.environ["PACKAGE_PATH"]) / "example/android/app/src/main/AndroidManifest.xml" + text = manifest.read_text() + for item in raw.split(): + key, _, value = item.partition("=") + if not re.fullmatch(r"[a-z0-9_]+", key) or value not in ("true", "false"): + raise SystemExit( + f"Invalid Android manifest metadata {item!r}, expected name=true|false." + ) + meta = f'' + pattern = re.compile( + rf'[ \t]*\n?' + ) + if pattern.search(text): + text = pattern.sub(" " + meta + "\n", text, count=1) + else: + needle = "" + if needle not in text: + raise SystemExit(f"{manifest} has no ") + text = text.replace(needle, " " + meta + "\n " + needle, 1) + print(f"AndroidManifest: {key} = {value}") + manifest.write_text(text) + PY - name: Pre-build APK # Build outside the emulator so the AVD does not boot and idle through the # whole Gradle build. `flutter test` below reuses this warm build cache. diff --git a/docs/cloud-messaging/receive.md b/docs/cloud-messaging/receive.md index 4b50f87ab2c8..baab3f05308c 100644 --- a/docs/cloud-messaging/receive.md +++ b/docs/cloud-messaging/receive.md @@ -203,7 +203,9 @@ To stop that on the next push, add this inside `` in Leave the entry out, or set it to `true`, and a stored handler still runs. `false` takes effect for a process started by a push, and it wins over a stored handler until the entry -is removed. +is removed. That push also deletes the stored registration, so taking the entry out later +does not bring the old handler back. The app has to open and call `onBackgroundMessage` +again. Set `android:value`. An `android:resource` value is ignored. #### Web {:#web} {:#web} diff --git a/packages/firebase_messaging/firebase_messaging/CHANGELOG.md b/packages/firebase_messaging/firebase_messaging/CHANGELOG.md index ac49b3c0f43c..bfdf97ea47d1 100644 --- a/packages/firebase_messaging/firebase_messaging/CHANGELOG.md +++ b/packages/firebase_messaging/firebase_messaging/CHANGELOG.md @@ -1,7 +1,3 @@ -## 17.0.2 - - - **FIX**(messaging,android): do not start the background service when no `onBackgroundMessage` handler is registered ([#18940](https://github.com/firebase/flutterfire/issues/18940)). - ## 17.0.1 - **FIX**(android): replace Groovy space-assignment in plugin build.gradle files ([#18837](https://github.com/firebase/flutterfire/issues/18837)). ([09e913ac](https://github.com/firebase/flutterfire/commit/09e913acd98fa25ea6ff547141e7caf421b7b02d)) diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java index f6fcb0047a83..66552a7baf57 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java @@ -13,6 +13,7 @@ import android.os.Parcel; import android.util.Log; import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; import com.google.firebase.messaging.RemoteMessage; import io.flutter.FlutterInjector; import io.flutter.embedding.engine.FlutterEngine; @@ -78,6 +79,11 @@ public boolean isNotRunning() { return !isCallbackDispatcherReady.get(); } + @VisibleForTesting + boolean isolateStartRequested() { + return isBackgroundIsolateStarted.get(); + } + private void onInitialized() { isCallbackDispatcherReady.set(true); FlutterFirebaseMessagingBackgroundService.onInitialized(); diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java index 0f2ffcd11722..07775c93f7ab 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundService.java @@ -9,6 +9,7 @@ import android.os.Handler; import android.util.Log; import androidx.annotation.NonNull; +import androidx.annotation.VisibleForTesting; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -81,7 +82,6 @@ public void onCreate() { BackgroundHandlerStartDecision.Action action = FlutterFirebaseMessagingBackgroundGate.decide(this); if (action == BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR) { - // onCreate runs on the main thread, so the preference write happens off it. FlutterFirebaseMessagingBackgroundGate.clearHandlesAsync(this); } if (action != BackgroundHandlerStartDecision.Action.START) { @@ -90,6 +90,16 @@ public void onCreate() { flutterBackgroundExecutor.startBackgroundIsolate(); } + @VisibleForTesting + static boolean isolateStartRequested() { + return flutterBackgroundExecutor != null && flutterBackgroundExecutor.isolateStartRequested(); + } + + @VisibleForTesting + static void resetExecutorForTests() { + flutterBackgroundExecutor = null; + } + /** * Executes a Dart callback, as specified within the incoming {@code intent}. * diff --git a/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java index 9be6ad6136ed..af09bcf95ed7 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java @@ -42,6 +42,7 @@ public void setUp() { preferences().edit().clear().commit(); FlutterFirebaseMessagingReceiver.notifications.clear(); JobIntentService.sClassWorkEnqueuer.clear(); + FlutterFirebaseMessagingBackgroundService.resetExecutorForTests(); } @After @@ -91,6 +92,18 @@ public void manifestFalseSkipsAStoredHandlerAndClearsIt() throws Exception { new FlutterFirebaseMessagingBackgroundExecutor().isDartBackgroundHandlerRegistered()); } + @Test + public void manifestFalseUnregistersTheHandlerWhileTheHandleIsStillStored() { + writeHandles(42L, 99L); + setManifestValue(Boolean.FALSE); + + assertFalse( + new FlutterFirebaseMessagingBackgroundExecutor().isDartBackgroundHandlerRegistered()); + assertEquals(42L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.CALLBACK_HANDLE_KEY)); + assertEquals( + 99L, readHandle(FlutterFirebaseMessagingBackgroundExecutor.USER_CALLBACK_HANDLE_KEY)); + } + @Test public void manifestStringFalseSkipsAStoredHandler() throws Exception { lockKeyguard(); @@ -120,6 +133,9 @@ public void serviceCreateWithManifestFalseDoesNotStartTheIsolate() throws Except setManifestValue(Boolean.FALSE); Robolectric.buildService(FlutterFirebaseMessagingBackgroundService.class).create(); + assertFalse(FlutterFirebaseMessagingBackgroundService.isolateStartRequested()); + assertFalse( + new FlutterFirebaseMessagingBackgroundExecutor().isDartBackgroundHandlerRegistered()); Shadows.shadowOf(Looper.getMainLooper()).idle(); FlutterFirebaseMessagingBackgroundGate.awaitClearForTests(); diff --git a/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt b/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt index 4eba59c6151f..d9a169f9119c 100644 --- a/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt +++ b/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt @@ -4,8 +4,10 @@ import android.app.ActivityManager import android.app.KeyguardManager import android.app.Notification import android.app.PendingIntent +import android.app.job.JobScheduler import android.content.Context import android.content.Intent +import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Handler @@ -110,6 +112,43 @@ class MainActivity : FlutterActivity() { secondEngine = null result.success(null) } + "backgroundHandlerEnabled" -> result.success(!backgroundHandlerDisabled()) + "probeBackgroundDelivery" -> { + val messageId = call.argument("messageId") + if (messageId.isNullOrEmpty()) { + result.error("INVALID_ARG", "messageId is required", null) + return@setMethodCallHandler + } + val hasPlugin = call.hasArgument("pluginHandle") + val hasUser = call.hasArgument("userHandle") + if (hasPlugin != hasUser) { + result.error( + "INVALID_ARG", + "pluginHandle and userHandle are set together", + null, + ) + return@setMethodCallHandler + } + val pluginHandle = call.argument("pluginHandle")?.toLong() + val userHandle = call.argument("userHandle")?.toLong() + // Home is delivered after this handler returns, so the probe waits + // on another thread until the process is no longer in the foreground. + Thread { + try { + result.success( + probeBackgroundDelivery(messageId, pluginHandle, userHandle), + ) + } catch (e: Exception) { + result.error("PROBE_FAILED", errorMessage(e), null) + } + } + .start() + try { + executeShell("input keyevent 3") + } catch (_: Exception) { + // The probe reports background=false when the app stays in front. + } + } else -> result.notImplemented() } } @@ -180,6 +219,103 @@ class MainActivity : FlutterActivity() { } } + /// Sends a data message the way Play services does, after the app has left + /// the foreground, and reports whether the background service started. + private fun probeBackgroundDelivery( + messageId: String, + pluginHandle: Long?, + userHandle: Long?, + ): Map { + if (pluginHandle != null && userHandle != null) { + callbackPreferences() + .edit() + .putLong(CALLBACK_HANDLE_KEY, pluginHandle) + .putLong(USER_CALLBACK_HANDLE_KEY, userHandle) + .commit() + } else { + callbackPreferences().edit().clear().commit() + } + try { + executeShell("logcat -c") + } catch (_: Exception) { + // A missing clear shows up as receiverRan=false. + } + val background = waitUntil { !isAppInForeground() } + if (background) { + val intent = + Intent("com.google.android.c2dm.intent.RECEIVE").apply { + putExtra("google.message_id", messageId) + putExtra("from", "e2e") + putExtra("test", "background-handler-gate") + } + FlutterFirebaseMessagingReceiver().onReceive(applicationContext, intent) + Thread.sleep(500) + } + val log = + try { + captureHostAdbShell( + "logcat -d -s FLTFireMsgReceiver:D FLTFireMsgService:V", + ) + } catch (_: Exception) { + "" + } + val report = + mapOf( + "background" to background, + "receiverRan" to log.contains("broadcast received for message"), + "serviceRan" to log.contains("FLTFireMsgService"), + "jobScheduled" to backgroundJobPending(), + "serviceRunning" to backgroundServiceRunning(), + "pluginHandle" to callbackPreferences().getLong(CALLBACK_HANDLE_KEY, 0L), + "userHandle" to callbackPreferences().getLong(USER_CALLBACK_HANDLE_KEY, 0L), + "handlerEnabled" to !backgroundHandlerDisabled(), + ) + try { + executeShell( + "am start -n $packageName/io.flutter.plugins.firebase.messaging.example.MainActivity", + ) + waitUntil { isAppInForeground() } + } catch (_: Exception) { + // The Dart side still receives the report. + } + return report + } + + private fun callbackPreferences() = + getSharedPreferences(CALLBACK_PREFERENCES, Context.MODE_PRIVATE) + + /// Explicit false in the application meta-data. Absent and true stay enabled. + private fun backgroundHandlerDisabled(): Boolean { + val info = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) + val raw = info.metaData?.get(BACKGROUND_HANDLER_METADATA_KEY) ?: return false + return when (raw) { + is Boolean -> !raw + is String -> raw.equals("false", ignoreCase = true) + else -> false + } + } + + private fun backgroundJobPending(): Boolean { + val scheduler = getSystemService(JobScheduler::class.java) ?: return false + return scheduler.allPendingJobs.any { it.id == BACKGROUND_JOB_ID } + } + + private fun backgroundServiceRunning(): Boolean { + val manager = getSystemService(ActivityManager::class.java) ?: return false + @Suppress("DEPRECATION") + return manager.getRunningServices(Integer.MAX_VALUE).any { + it.service.className == BACKGROUND_SERVICE_CLASS + } + } + + private fun waitUntil(condition: () -> Boolean): Boolean { + repeat(50) { + if (condition()) return true + Thread.sleep(100) + } + return condition() + } + /// Dismisses the lock screen if needed: the receiver only sends messages to /// onMessage while the app is in the foreground. Returns whether it is. private fun unlockAndCheckForeground(): Boolean { @@ -354,10 +490,15 @@ class MainActivity : FlutterActivity() { /// [android.os.NetworkOnMainThreadException] for socket I/O on the main /// thread, and that exception has a null message. private fun executeHostAdbShell(command: String) { + captureHostAdbShell(command) + } + + private fun captureHostAdbShell(command: String): String { + val output = arrayOfNulls(1) val error = arrayOfNulls(1) val thread = Thread { try { - executeHostAdbShellBlocking(command) + output[0] = executeHostAdbShellBlocking(command) } catch (e: Exception) { error[0] = e } @@ -368,9 +509,10 @@ class MainActivity : FlutterActivity() { throw IllegalStateException("adb shell timed out: $command") } error[0]?.let { throw it } + return output[0] ?: "" } - private fun executeHostAdbShellBlocking(command: String) { + private fun executeHostAdbShellBlocking(command: String): String { val socket = Socket() try { socket.connect(InetSocketAddress(EMULATOR_HOST_LOOPBACK, ADB_SERVER_PORT), ADB_TIMEOUT_MS) @@ -382,10 +524,16 @@ class MainActivity : FlutterActivity() { sendAdb(out, "shell:$command") readAdbStatus(input) // Drain command output so adbd does not see a premature close. + val captured = StringBuilder() val buffer = ByteArray(1024) - while (input.read(buffer) != -1) { - // discard + while (true) { + val read = input.read(buffer) + if (read < 0) { + break + } + captured.append(String(buffer, 0, read, StandardCharsets.UTF_8)) } + return captured.toString() } finally { socket.close() } @@ -453,5 +601,12 @@ class MainActivity : FlutterActivity() { const val EMULATOR_HOST_LOOPBACK = "10.0.2.2" const val ADB_SERVER_PORT = 5037 const val ADB_TIMEOUT_MS = 5000 + const val CALLBACK_PREFERENCES = "io.flutter.firebase.messaging.callback" + const val CALLBACK_HANDLE_KEY = "callback_handle" + const val USER_CALLBACK_HANDLE_KEY = "user_callback_handle" + const val BACKGROUND_HANDLER_METADATA_KEY = "firebase_messaging_background_handler_enabled" + const val BACKGROUND_JOB_ID = 2020 + const val BACKGROUND_SERVICE_CLASS = + "io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService" } } diff --git a/packages/firebase_messaging/firebase_messaging/example/integration_test/background_handler_opt_out_test.dart b/packages/firebase_messaging/firebase_messaging/example/integration_test/background_handler_opt_out_test.dart new file mode 100644 index 000000000000..deb78ee5d75e --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/example/integration_test/background_handler_opt_out_test.dart @@ -0,0 +1,51 @@ +// 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. + +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_messaging_example/firebase_options.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import 'remote_notification_delivery.dart'; +import 'report_test_results.dart'; + +/// Runs only when the example APK sets +/// `firebase_messaging_background_handler_enabled` to false. The default e2e +/// build leaves that entry out. +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + reportTestResultsToDriver(binding); + + setUpAll(() async { + await Firebase.initializeApp( + options: DefaultFirebaseOptions.currentPlatform, + ); + }); + + test('a stored handler is cleared and the background service does not start ' + 'when the manifest opt-out is set', () async { + expect( + await androidBackgroundHandlerEnabled(), + isFalse, + reason: + 'This file is for an APK whose manifest sets ' + 'firebase_messaging_background_handler_enabled to false.', + ); + + final probe = await probeBackgroundDelivery( + 'opt-out-${DateTime.now().microsecondsSinceEpoch}', + pluginHandle: 42, + userHandle: 99, + ); + + expect(probe['background'], isTrue); + expect(probe['receiverRan'], isTrue); + expect(probe['serviceRan'], isFalse); + expect(probe['jobScheduled'], isFalse); + expect(probe['serviceRunning'], isFalse); + expect(probe['pluginHandle'], 0); + expect(probe['userHandle'], 0); + }, skip: kIsWeb || defaultTargetPlatform != TargetPlatform.android); +} 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 145273088f51..b64ce8ad0a77 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 @@ -390,5 +390,18 @@ void main() { skip: kIsWeb, ); }); + + test('a background message with no registered handler does not start ' + 'the background service', () async { + final probe = await probeBackgroundDelivery( + 'no-handler-${DateTime.now().microsecondsSinceEpoch}', + ); + + expect(probe['background'], isTrue); + expect(probe['receiverRan'], isTrue); + expect(probe['serviceRan'], isFalse); + expect(probe['jobScheduled'], isFalse); + expect(probe['serviceRunning'], isFalse); + }, skip: kIsWeb || defaultTargetPlatform != TargetPlatform.android); }); } diff --git a/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart b/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart index e4879c524f2f..ba7d318f28ce 100644 --- a/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart +++ b/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart @@ -39,6 +39,37 @@ Future> deliverRemoteNotification( return delivery!; } +/// Whether the installed app left the background handler enabled. Absent and +/// `true` both count as enabled. +Future androidBackgroundHandlerEnabled() async { + final enabled = await _remoteNotificationsChannel.invokeMethod( + 'backgroundHandlerEnabled', + ); + return enabled ?? true; +} + +/// Delivers one data message after the app has left the foreground, the way a +/// push does when nobody is using the app. Returns whether that happened in +/// the background, whether the receiver ran, and whether the background +/// service or its job started. +/// +/// Pass [pluginHandle] and [userHandle] to store a handler first. Omit both +/// and any stored handler is cleared before the push. +Future> probeBackgroundDelivery( + String messageId, { + int? pluginHandle, + int? userHandle, +}) async { + final probe = await _remoteNotificationsChannel + .invokeMapMethod('probeBackgroundDelivery', { + 'messageId': messageId, + if (pluginHandle != null) 'pluginHandle': pluginHandle, + if (userHandle != null) 'userHandle': userHandle, + }) + .timeout(const Duration(seconds: 20)); + return probe!; +} + /// Hands data messages to the plugin's broadcast receiver back to back, like /// Google Play services does when several pushes arrive at once. Fails if the /// app did not count as in the foreground, where messages go to `onMessage`. From a8c41d2f4bce14aaa0336eb06e29b23619544868 Mon Sep 17 00:00:00 2001 From: Jude Kwashie Date: Wed, 11 Nov 2026 12:16:55 +0000 Subject: [PATCH 3/5] chore(messaging): drop comments that restate the background gate The review flagged three comments that only repeat the null check, the manifest default, and the enabled fallback. --- .../messaging/FlutterFirebaseMessagingBackgroundExecutor.java | 1 - .../flutter/plugins/firebase/messaging/example/MainActivity.kt | 1 - .../example/integration_test/remote_notification_delivery.dart | 2 -- 3 files changed, 4 deletions(-) diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java index 66552a7baf57..9118e42cfd4b 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundExecutor.java @@ -283,7 +283,6 @@ private long getPluginCallbackHandle() { return readPluginCallbackHandle(ContextHolder.getApplicationContext()); } - /** Returns the stored plugin callback handle, or 0 when {@code context} is null or unset. */ static long readPluginCallbackHandle(Context context) { if (context == null) { return 0L; diff --git a/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt b/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt index d9a169f9119c..e366e85d8389 100644 --- a/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt +++ b/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt @@ -284,7 +284,6 @@ class MainActivity : FlutterActivity() { private fun callbackPreferences() = getSharedPreferences(CALLBACK_PREFERENCES, Context.MODE_PRIVATE) - /// Explicit false in the application meta-data. Absent and true stay enabled. private fun backgroundHandlerDisabled(): Boolean { val info = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) val raw = info.metaData?.get(BACKGROUND_HANDLER_METADATA_KEY) ?: return false diff --git a/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart b/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart index ba7d318f28ce..30300c5c52b3 100644 --- a/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart +++ b/packages/firebase_messaging/firebase_messaging/example/integration_test/remote_notification_delivery.dart @@ -39,8 +39,6 @@ Future> deliverRemoteNotification( return delivery!; } -/// Whether the installed app left the background handler enabled. Absent and -/// `true` both count as enabled. Future androidBackgroundHandlerEnabled() async { final enabled = await _remoteNotificationsChannel.invokeMethod( 'backgroundHandlerEnabled', From 073cebe309e39b3385c6679d760e7412c1313a65 Mon Sep 17 00:00:00 2001 From: Jude Kwashie Date: Wed, 11 Nov 2026 12:18:58 +0000 Subject: [PATCH 4/5] chore(messaging): drop the remaining comments that restate the gate The review asked to keep only the notes the code cannot show: how Android stores the manifest value, and that preference writes stay off the main thread. --- .../firebase/messaging/BackgroundHandlerStartDecision.java | 6 ------ .../messaging/FlutterFirebaseMessagingBackgroundGate.java | 5 ----- .../plugins/firebase/messaging/example/MainActivity.kt | 2 -- 3 files changed, 13 deletions(-) diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java index 7309e89f9c18..7fe8e190a72d 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java @@ -4,12 +4,6 @@ package io.flutter.plugins.firebase.messaging; -/** - * Whether a background message should start the Dart handler. - * - *

{@code manifestEnabled} is null when the app manifest does not set {@code - * firebase_messaging_background_handler_enabled}. - */ final class BackgroundHandlerStartDecision { enum Action { START, diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java index 8e6c4fa61453..1adca3611802 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java @@ -15,10 +15,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -/** - * Reads the stored callback handle and the manifest opt-out, and decides whether this process - * should start the background Dart handler. - */ final class FlutterFirebaseMessagingBackgroundGate { static final String METADATA_KEY = "firebase_messaging_background_handler_enabled"; @@ -38,7 +34,6 @@ static BackgroundHandlerStartDecision.Action decide(Context context) { manifestEnabled(appContext)); } - /** True when the manifest opts out, including before the stored handles have been deleted. */ static boolean handlerDisabled(Context context) { return Boolean.FALSE.equals(manifestEnabled(applicationContext(context))); } diff --git a/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt b/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt index e366e85d8389..9a61956cc300 100644 --- a/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt +++ b/packages/firebase_messaging/firebase_messaging/example/android/app/src/main/kotlin/io/flutter/plugins/firebase/messaging/example/MainActivity.kt @@ -219,8 +219,6 @@ class MainActivity : FlutterActivity() { } } - /// Sends a data message the way Play services does, after the app has left - /// the foreground, and reports whether the background service started. private fun probeBackgroundDelivery( messageId: String, pluginHandle: Long?, From ffc1ae7a84f39385f5db48f4348b1a50c93082e5 Mon Sep 17 00:00:00 2001 From: Jude Kwashie Date: Thu, 12 Nov 2026 10:02:19 +0000 Subject: [PATCH 5/5] fix(messaging,android): log a skipped background push The receiver returned without a log when no handler was registered, so the warning people search for never appeared. Also state that every install with a stored handler keeps starting the engine. --- docs/cloud-messaging/receive.md | 5 +++-- .../messaging/FlutterFirebaseMessagingReceiver.java | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/cloud-messaging/receive.md b/docs/cloud-messaging/receive.md index baab3f05308c..e2ebffeb3f36 100644 --- a/docs/cloud-messaging/receive.md +++ b/docs/cloud-messaging/receive.md @@ -189,8 +189,9 @@ A few things to be aware of: ##### Turning off the Android background handler {: #android-background-handler-opt-out} Registration is stored on the device. Removing `onBackgroundMessage` from `main()` does not -clear it, and a push can start the process without running `main()`. Installs that have not -been opened since the update still start a background Flutter engine. +clear it, and a push can start the process without running `main()`. So every install that +registered a handler keeps starting a background Flutter engine on pushes, including installs +that have not been opened since the update. To stop that on the next push, add this inside `` in `android/app/src/main/AndroidManifest.xml`: diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java index e1e5568224ac..229b2da9465e 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingReceiver.java @@ -82,6 +82,15 @@ public void onReceive(Context context, Intent intent) { FlutterFirebaseMessagingBackgroundGate.decide(context); if (action == BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR) { FlutterFirebaseMessagingBackgroundGate.clearHandles(context); + Log.d( + TAG, + "A background message was ignored because" + + " firebase_messaging_background_handler_enabled is false."); + } else if (action == BackgroundHandlerStartDecision.Action.SKIP) { + Log.d( + TAG, + "A background message could not be handled in Dart as no onBackgroundMessage" + + " handler has been registered."); } if (action != BackgroundHandlerStartDecision.Action.START) { return;