Skip to content

[Firebase Messaging] Background handler isn't being called #2696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
itismejy opened this issue Jun 4, 2020 · 7 comments
Closed

[Firebase Messaging] Background handler isn't being called #2696

itismejy opened this issue Jun 4, 2020 · 7 comments
Labels
plugin: messaging Stale Issue with no recent activity type: bug Something isn't working

Comments

@itismejy
Copy link

itismejy commented Jun 4, 2020

Defining a background handler function in the .configure that will call when a notification is received while the app is in the background, but the handler isn't being called at all (nothing is printed).

The message in the terminal is "Notification Channel set in AndroidManifest.xml has not been created by the app. Default value will be used."

@itismejy itismejy changed the title [Firebase Messaging] Background handler isn't being called, can see notification but "Notification Channel set in AndroidManifest.xml has not been created by the app. Default value will be used." [Firebase Messaging] Background handler isn't being called Jun 4, 2020
@ened
Copy link
Contributor

ened commented Jun 4, 2020

@itismejy could you give my fork a test run:

dependency_overrides:
  firebase_messaging:
    git:
      url: https://github.com/ened/flutterfire.git
      path: packages/firebase_messaging
      ref: 6237973ce4b0aae5de0d828c3ba073cc04d50cea

I had similar problems and refactored the plugin a little bit. The open PR is #261.

@iapicca
Copy link

iapicca commented Jun 5, 2020

Hi @itismejy
Can you please provide your flutter doctor -v,
your flutter run --verbose,
your pubspec.yaml
and a minimal reproducible code sample.
Thank you

@iapicca iapicca added the blocked: customer-response Waiting for customer response, e.g. more information was requested. label Jun 5, 2020
@TabooSun
Copy link
Contributor

TabooSun commented Jun 15, 2020

I am having the same issue,
This is the flutter doctor -v:

doctor
[✓] Flutter (Channel stable, v1.17.2, on Mac OS X 10.15.5 19F101, locale en-GB)
    • Flutter version 1.17.2 at /Users/kahwaimok/Development/flutter
    • Framework revision 5f21edf8b6 (3 weeks ago), 2020-05-28 12:44:12 -0700
    • Engine revision b851c71829
    • Dart version 2.8.3

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/kahwaimok/Library/Android/sdk
    • Platform android-29, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.5, Build version 11E608c
    • CocoaPods version 1.8.4

[✓] Android Studio (version 4.0)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 46.0.2
    • Dart plugin version 193.7361
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] VS Code (version 1.46.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.11.0

[✓] Connected device (1 available)
    • SM N960F • 192.168.1.251:5555 • android-arm64 • Android 10 (API 29)

• No issues found!

This is the flutter run --verbose output:

flutter run --verbose
An Observatory debugger and profiler on SM N960F is available at: http://127.0.0.1:62356/kbBmN8F-8es=/
[+18824 ms] W/althmetrics.Ap(10878): Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist, reflection, allowed)
[        ] W/althmetrics.Ap(10878): Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist, reflection, allowed)
[        ] W/althmetrics.Ap(10878): Accessing hidden method Landroid/os/WorkSource;->size()I (greylist, reflection, allowed)
[        ] W/althmetrics.Ap(10878): Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
[        ] W/althmetrics.Ap(10878): Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
[  +57 ms] W/FirebaseMessaging(10878): Unable to log event: analytics library is missing
[  +15 ms] W/FirebaseMessaging(10878): Unable to log event: analytics library is missing
[  +59 ms] I/flutter (10878): AppPushs onMessage : {notification: {title: this is a title, body: this is a body}, data: {status: done, id: 1, click_action: FLUTTER_NOTIFICATION_CLICK}}
[+5458 ms] D/ViewRootImpl@cdf05bc[MainActivity](10878): MSG_WINDOW_FOCUS_CHANGED 0 1
[        ] D/InputMethodManager(10878): prepareNavigationBarInfo() DecorView@d8b7090[MainActivity]
[        ] D/InputMethodManager(10878): getNavigationBarColor() -855310
[ +125 ms] D/InputTransport(10878): Input channel destroyed: 'ClientS', fd=97
[  +89 ms] D/SurfaceView(10878): onWindowVisibilityChanged(8) false io.flutter.embedding.android.FlutterSurfaceView{dc0889a V.E...... ........ 0,0-1440,2960} of ViewRootImpl@cdf05bc[MainActivity]
[        ] D/SurfaceView(10878): surfaceDestroyed callback.size 1 #2 io.flutter.embedding.android.FlutterSurfaceView{dc0889a V.E...... ........ 0,0-1440,2960}
[   +7 ms] W/libEGL  (10878): EGLNativeWindowType 0x7b8bf9b010 disconnect failed
[        ] D/SurfaceView(10878): remove() io.flutter.embedding.android.FlutterSurfaceView{dc0889a V.E...... ........ 0,0-1440,2960} Surface(name=SurfaceView - com.App.App/com.App.App.MainActivity@dc0889a@0)/@0xf432f9b
[   +7 ms] W/libEGL  (10878): EGLNativeWindowType 0x7c1521c710 disconnect failed
[  +17 ms] D/ViewRootImpl@cdf05bc[MainActivity](10878): Relayout returned: old=(0,0,1440,2960) new=(0,0,1440,2960) req=(1440,2960)8 dur=8 res=0x5 s={false 0} ch=true
[        ] D/ViewRootImpl@cdf05bc[MainActivity](10878): stopped(true) old=false
[        ] D/SurfaceView(10878): windowStopped(true) false io.flutter.embedding.android.FlutterSurfaceView{dc0889a V.E...... ........ 0,0-1440,2960} of ViewRootImpl@cdf05bc[MainActivity]
[+4231 ms] W/FirebaseMessaging(10878): Unable to log event: analytics library is missing
[  +15 ms] W/FirebaseMessaging(10878): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.

This is the pubspec.yaml:

pubspec
name: App
description: A new Flutter application.

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  firebase_messaging: ^6.0.16
  firebase_core: ^0.4.5
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter


flutter:
  uses-material-design: true

My Android Manifest:

<application
        android:name=".PushApplication"
        android:label="App"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>

This is my PushApplication.kt:

native
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService


class PushApplication : FlutterApplication(), PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this)
    }

    override fun registerWith(registry: PluginRegistry?) {
//        FirebaseMessagingPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
        FirebaseCloudMessagingPluginRegistrant.registerWith(registry!!)
    }
}

This is my FirebaseCloudMessagingPluginRegistrant.kt

import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin

class FirebaseCloudMessagingPluginRegistrant {
    companion object {
        fun registerWith(registry: PluginRegistry) {
            if (alreadyRegisteredWith(registry)) {
                return;
            }
            FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
        }

        fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
            val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
            if (registry.hasPlugin(key)) {
                return true
            }
            registry.registrarFor(key)
            return false
        }
    }
}

This is my main.dart:

code sample
import 'package:App/app_push.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(AppPush(child: MyApp()));
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

This is my app_push.dart

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class AppPush extends StatefulWidget {
  final Widget child;

  AppPush({
    Key key,
    this.child,
  }) : super(key: key);

  @override
  _AppPushState createState() => _AppPushState();
}

class _AppPushState extends State<AppPush> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _configurePushNotification();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }

  Future<void> _configurePushNotification() async {
    final token = await _firebaseMessaging.getToken();
    print('FCM token: $token');
    _firebaseMessaging.configure(
      onLaunch: (Map<String, dynamic> message) {
        print('AppPushs onLaunch : $message');
        return;
      },
      onMessage: (Map<String, dynamic> message) {
        print('AppPushs onMessage : $message');
        return;
      },
      onResume: (Map<String, dynamic> message) {
        print('AppPushs onResume : $message');
        return;
      },
      onBackgroundMessage: _onBackgroundMessage,
    );
    await _firebaseMessaging
        .requestNotificationPermissions(const IosNotificationSettings(
      sound: true,
      badge: true,
      alert: true,
    ));
  }
}

Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  print('AppPushs onBackgroundMessage : $message'); // not triggerring

  return Future.value();
}

@iapicca iapicca added plugin: messaging type: bug Something isn't working and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Jun 19, 2020
@jeanadam
Copy link

I am also having same problem, although onBackgroundMessage is configured it is never triggered. OnMessage, OnLaunch and onResume are working fine.

@deep01code
Copy link

I found out that this behavior is not always the same depending on the device type that I am testing my code on. Some devices run without any issues. It is a strange bug

@ncuillery
Copy link

Not sure but it may be related to this Firebase SDK issue: firebase/firebase-android-sdk#361

My background handler is not called, but this error shows up in logcat at the very right moment when the notification appears in the notification tray.

@Salakar Salakar added the Stale Issue with no recent activity label Apr 1, 2021
@russellwheatley
Copy link
Member

Closing in favour of trying the latest messaging version which has been been heavily reworked, along with documentation, since this issue was raised: https://firebase.flutter.dev/docs/messaging/overviewIf you still have a problem please raise a new GitHub issue with up to date information and code snippets if possible. Thanks.

@firebase firebase locked and limited conversation to collaborators May 17, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
plugin: messaging Stale Issue with no recent activity type: bug Something isn't working
Projects
None yet
Development

No branches or pull requests

9 participants