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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .github/workflows/e2e_tests_messaging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
37 changes: 37 additions & 0 deletions .github/workflows/reusable_e2e_android.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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'<meta-data android:name="{key}" android:value="{value}" />'
pattern = re.compile(
rf'[ \t]*<meta-data\s+android:name="{re.escape(key)}"\s+android:value="(?:true|false)"\s*/>\n?'
)
if pattern.search(text):
text = pattern.sub(" " + meta + "\n", text, count=1)
else:
needle = "</application>"
if needle not in text:
raise SystemExit(f"{manifest} has no </application>")
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.
Expand Down
22 changes: 22 additions & 0 deletions docs/cloud-messaging/receive.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<application>` in
`android/app/src/main/AndroidManifest.xml`:

```xml
<meta-data
android:name="firebase_messaging_background_handler_enabled"
android:value="false" />
```

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}

Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);

Expand Down Expand Up @@ -78,6 +79,11 @@ public boolean isNotRunning() {
return !isCallbackDispatcherReady.get();
}

@VisibleForTesting
boolean isolateStartRequested() {
return isBackgroundIsolateStarted.get();
}

private void onInitialized() {
isCallbackDispatcherReady.set(true);
FlutterFirebaseMessagingBackgroundService.onInitialized();
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
Comment on lines +99 to +102

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

On some custom or unstable Android ROMs, calling PackageManager methods can throw other runtime exceptions (such as DeadSystemException or general RuntimeException). It is safer to catch Exception generally to prevent unexpected crashes when reading manifest metadata.

Suggested change
} catch (PackageManager.NameNotFoundException exception) {
Log.w(TAG, "Could not read " + METADATA_KEY + " from the manifest.", exception);
return null;
}
} catch (Exception 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}.
*
Expand Down
Loading
Loading