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 7311ec0a428d..e2ebffeb3f36 100644 --- a/docs/cloud-messaging/receive.md +++ b/docs/cloud-messaging/receive.md @@ -186,6 +186,28 @@ 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()`. 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`: + +```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. 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/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..7fe8e190a72d --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/BackgroundHandlerStartDecision.java @@ -0,0 +1,46 @@ +// 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; + +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..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 @@ -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; @@ -36,8 +37,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); @@ -78,6 +79,11 @@ public boolean isNotRunning() { return !isCallbackDispatcherReady.get(); } + @VisibleForTesting + boolean isolateStartRequested() { + return isBackgroundIsolateStarted.get(); + } + private void onInitialized() { isCallbackDispatcherReady.set(true); FlutterFirebaseMessagingBackgroundService.onInitialized(); @@ -172,6 +178,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 +280,25 @@ 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()); + } + + 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..1adca3611802 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGate.java @@ -0,0 +1,113 @@ +// 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; + +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)); + } + + 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..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; @@ -78,9 +79,27 @@ public void onCreate() { if (flutterBackgroundExecutor == null) { flutterBackgroundExecutor = new FlutterFirebaseMessagingBackgroundExecutor(); } + BackgroundHandlerStartDecision.Action action = + FlutterFirebaseMessagingBackgroundGate.decide(this); + if (action == BackgroundHandlerStartDecision.Action.SKIP_AND_CLEAR) { + FlutterFirebaseMessagingBackgroundGate.clearHandlesAsync(this); + } + if (action != BackgroundHandlerStartDecision.Action.START) { + return; + } 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/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..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 @@ -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,24 @@ 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); + 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; + } + Intent onBackgroundMessageIntent = new Intent(context, FlutterFirebaseMessagingBackgroundService.class); @@ -151,4 +171,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..af09bcf95ed7 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingBackgroundGateTest.java @@ -0,0 +1,218 @@ +// 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(); + FlutterFirebaseMessagingBackgroundService.resetExecutorForTests(); + } + + @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 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(); + 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(); + assertFalse(FlutterFirebaseMessagingBackgroundService.isolateStartRequested()); + assertFalse( + new FlutterFirebaseMessagingBackgroundExecutor().isDartBackgroundHandlerRegistered()); + 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; + } +} 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..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 @@ -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,100 @@ class MainActivity : FlutterActivity() { } } + 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) + + 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 +487,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 +506,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 +521,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 +598,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..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,6 +39,35 @@ Future> deliverRemoteNotification( return delivery!; } +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`.