首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >flutter: on background message handler未被调用

flutter: on background message handler未被调用
EN

Stack Overflow用户
提问于 2020-06-02 01:54:27
回答 2查看 5.1K关注 0票数 1

我已经在我的应用程序中实现了firebase云消息传递和firebase函数,并使用flutter本地通知,并添加了showNotifications函数来创建通道ID并更改其重要性和优先级,这样我就可以提前得到通知(banner),但由于某些原因,当我从firestore发送消息时,onbackgroundmessagehandler回调函数不会被调用。

下面是我的代码:

代码语言:javascript
运行
复制
  Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
      print('background message handler');
      return await _TabsScreenState()._showNotification(message);
    }

    class TabsScreen extends StatefulWidget {
      static const String id = '/tabs screen';


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

    class _TabsScreenState extends State<TabsScreen> {
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          FlutterLocalNotificationsPlugin();
      FirebaseMessaging _fcm = FirebaseMessaging();
      Firestore _fireStore = Firestore.instance;

      void _onSaved() async {
        String myToken = await _fcm.getToken();

        if (myToken != null) {
          var tokenRef = _fireStore.collection('tokens').document(myToken);
          print(myToken);

          await tokenRef.setData({
            'token': myToken,
            'createdAt': DateTime.now(),
            'platform': Platform.operatingSystem,
          });
        }
      }

      Future _showNotification(Map<String, dynamic> message) async {
        print('show notifications');
        var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
          'channel id',
          'channel name',
          'channel desc',
          importance: Importance.Max,
          priority: Priority.High,
        );

        var platformChannelSpecifics =
            new NotificationDetails(androidPlatformChannelSpecifics, null);
        await flutterLocalNotificationsPlugin.show(
          0,
          message['notifications']['title'],
          'hi',
          platformChannelSpecifics,
          payload: 'default sound',
        );
      }

      Future selectNotification(String payload) async {
        await flutterLocalNotificationsPlugin.cancelAll();
      }


      void initState() {
        var initializationSettingsAndroid =
            AndroidInitializationSettings('@mipmap/ic_launcher');
        var initializationSettings =
            InitializationSettings(initializationSettingsAndroid, null);
        flutterLocalNotificationsPlugin.initialize(initializationSettings,
            onSelectNotification: selectNotification);
        _onSaved();
        _fcm.configure(
            onBackgroundMessage: myBackgroundMessageHandler,
            onMessage: (Map<String, dynamic> message) async {
              print("On Message: $message");
              print(message['data']['message']);
              showDialog(
                context: context,
                builder: (ctx) {
                  return AlertDialog(
                    content: ListTile(
                      title: Text(message['data']['message']),
                    ),
                    actions: <Widget>[
                      FlatButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('Ok'),
                      )
                    ],
                  );
                },
              );
            },
            onResume: (Map<String, dynamic> resume) async {
              print("on resume: $resume");
            },
            onLaunch: (Map<String, dynamic> launch) async {
              print("on launch: $launch");
            });



      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
          title: Text("My App"),
        );
      }
    }

这是我的andoird清单:

代码语言:javascript
运行
复制
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tamataapp">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. "io.flutter.app.FlutterApplication" -->
    <application
        android:name=".Application"
        android:label="tamataapp"
        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">
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="default_notification_channel_id”>Channel ID"/>
            <!-- 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"/>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </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" />
        <service
            android:name=".java.MyFirebaseMessagingService"
            android:exported="false">
        </service>
    </application>
</manifest>

下面是我的index.js代码:

代码语言:javascript
运行
复制
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

var newData;

exports.messageTrigger = functions.firestore.document('messages/{messagesId}').onCreate(async (snapshot, context) => {


    if (snapshot.empty) {
        console.log('No Devices');
        return;
    }

    newData = snapshot.data();

    const deviceIdTokens = await admin
        .firestore()
        .collection('tokens')
        .get();

    var tokenm = [];

    for (var one of deviceIdTokens.docs) {
        tokenm.push(one.data().token);
    }
    const payload = {
        data: {
          click_action: 'FLUTTER_NOTIFICATION_CLICK',
          message: newData.message,

        }
      };



    try {
        const response = await admin.messaging().sendToDevice(tokenm, payload);
        console.log('Notification sent successfully');
    } catch (err) {
        console.log(err);
    }
});
EN

回答 2

Stack Overflow用户

发布于 2020-10-16 13:07:28

如果您在JSON中发送notification,则onBackgroundMessage不起作用,因此请从您的JSON中删除notification以使onBackgroundMessage起作用。

如果在你的JSON中设置了notifications,你会在手机中看到默认的提示信息(横幅),onBackgroundMessage不会运行。

票数 3
EN

Stack Overflow用户

发布于 2020-06-02 15:44:20

您使用的是什么版本的firebase_messaging?

来自pub页面https://pub.dev/packages/flutter_local_notifications

与firebase_messaging的

兼容性

以前,有一些问题阻碍了这个插件与firebase_messaging插件一起正常工作。这意味着来自每个插件的回调可能不会被调用。firebase_messaging的版本6.0.13应该可以解决这个问题,所以请降低对firebase_messaging的依赖,并按照firebase_messaging的自述文件中介绍的步骤操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62138049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档