Flutter:如何使用 fcm 以编程方式发送推送通知 [英] Flutter: How can i send push notification programmatically with fcm

查看:26
本文介绍了Flutter:如何使用 fcm 以编程方式发送推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个聊天应用程序,如果此人有新消息,我想使用 fcm 发送通知,但我不知道如何继续.我发现的所有教程都用于从 firebase 发送消息.但是我想在有新消息给这个人时自动发送

解决方案

如果你使用 firebase,一个可能的解决方法应该是这样的:

您需要为特定用户存储每个 firebase FCM 令牌(需要在此处考虑到用户可以从多个设备同时登录其帐户),以便您可以存储 userId 和他的 deviceUniqueId on flutter 你可以从 device_info https://pub.dev/packages/device_info:

 字符串标识符;final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();尝试 {如果(平台.isAndroid){var build = await deviceInfoPlugin.androidInfo;标识符 = build.id.toString();} else if (Platform.isIOS) {var data = await deviceInfoPlugin.iosInfo;identifier = data.identifierForVendor;//iOS的UUID}} on PlatformException {print('获取平台版本失败');}

然后要获取 Firebase 为每个设备提供的唯一 CFM 令牌,您可以使用 Firebase firebase_messaging 插件(https://pub.dev/packages/firebase_messaging) getToken() 并将令牌插入到 firestore(或其他要存储它的数据库)

 FirebaseMessaging firebaseMessaging = new FirebaseMessaging();firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(sound: true, 徽章: true, alert: true));firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings 设置) {打印(注册设置:$设置");});firebaseMessaging.getToken().then((token){print('--- Firebase 在这里使用 ---');Firestore.instance.collection(constant.userID).document(identifier).setData({'token': token});打印(令牌);});

之后,您可以为一个用户插入一个或多个连接到多个设备的 FCM 令牌.1 个用户 ... n 个设备,1 个设备 ... 1 个唯一令牌,用于从 Firebase 获取推送通知.

当有人有新消息时自动发送:现在您需要调用 Firestore API(确实非常快,但需要注意您在这里使用的计划限制) 或另一个 API 调用,如果您将令牌存储到另一个数据库,以便为每个用户获取令牌/令牌并发送推送通知.

要从 flutter 发送推送通知,您可以使用 Future 异步函数.Ps:我在这里传递一个 List 作为参数,以便使用 "registration_ids" 而不是 "to" 并将推送通知发送到多个令牌,如果用户已在多台设备上登录.

未来callOnFcmApiSendPushNotifications(List  userToken) async {最终 postUrl = 'https://fcm.googleapis.com/fcm/send';最终数据 = {registration_ids":用户令牌,collapse_key":type_a",通知":{"title": 'NewTextTitle',身体": 'NewTextBody',}};最终标题 = {'内容类型':'应用程序/json','授权':constant.firebaseTokenAPIFCM//'key=YOUR_SERVER_KEY'};最终回复 = 等待 http.post(postUrl,正文:json.encode(数据),编码:Encoding.getByName('utf-8'),标题:标题);如果(响应.状态代码 == 200){//成功后做某事打印('测试好推CFM');返回真;} 别的 {print('CFM 错误');//失败时做某事返回假;}}

您还可以查看邮递员的邮件,以便进行一些测试.POST 请求在标题上添加:

  1. key Authorization with value key=AAAAO........//项目概览 ->云消息传递 ->服务器密钥
  2. key Content-Type with value application/json

并在身体上添加

<代码>{registration_ids":[ "userUniqueToken1", "userUniqueToken2",... ],collapse_key":type_a",通知":{身体":测试帖",标题":推送通知 E"}}

registration_ids" 将其发送到多个令牌(同一用户同时登录多个设备)to" 以便将其发送到单个令牌(每个用户一台设备/或始终更新与其设备连接并具有 1 个令牌 ... 1 个用户的用户令牌)>

我正在对响应进行编辑,以便在可信环境或服务器上添加FCM服务器密钥非常重要!

I'm creating a chat application and i want to use fcm to send notification if the person has a new message, but i don't know how to proceed. All the tutorials i found use to send the message from firebase. But i want to send it automatically when there is a new message for the person

解决方案

A possible workaround if you use firebase should be like this:

You need to store each firebase FCM token for a specific user (need to take in account here that a user can log in at the same time on his account from multiple devices) so you can store the userId and his deviceUniqueId on flutter you can get it from device_info https://pub.dev/packages/device_info:

  String identifier;
  final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
  try {
    if (Platform.isAndroid) {
      var build = await deviceInfoPlugin.androidInfo;
      identifier = build.id.toString();
    } else if (Platform.isIOS) {
      var data = await deviceInfoPlugin.iosInfo;
      identifier = data.identifierForVendor;//UUID for iOS
    }
  } on PlatformException {
    print('Failed to get platform version');
  }

and after that to get the unique CFM token that Firebase provide for each device, you can get it using Firebase firebase_messaging plugin (https://pub.dev/packages/firebase_messaging) getToken() and insert the token to firestore (or an other database you want to store it)

  FirebaseMessaging firebaseMessaging = new FirebaseMessaging();

  firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true));
  firebaseMessaging.onIosSettingsRegistered
      .listen((IosNotificationSettings settings) {
    print("Settings registered: $settings");
  });

  firebaseMessaging.getToken().then((token){

    print('--- Firebase toke here ---');
    Firestore.instance.collection(constant.userID).document(identifier).setData({ 'token': token});
    print(token);

  });

After that you can insert one or more FCM token connected to multiple device for one user. 1 user ... n devices , 1 device ... 1 unique token to get push notifications from Firebase.

send it automatically when there is a new message for the person : now you need to call the Firestore API(is very fast indeed but need to be careful about the plan limit that you are using here) or another API call if you store the token to another db, in order to get the token/tokens for each user and send the push notifications.

To send the push notification from flutter you can use a Future async function. P.s: I'm passing as argument a List here in order to use "registration_ids" instead of "to" and send the push notification to multiple tokens if the user has been logged in on multiple devices.

Future<bool> callOnFcmApiSendPushNotifications(List <String> userToken) async {

  final postUrl = 'https://fcm.googleapis.com/fcm/send';
  final data = {
    "registration_ids" : userToken,
    "collapse_key" : "type_a",
    "notification" : {
      "title": 'NewTextTitle',
      "body" : 'NewTextBody',
    }
  };

  final headers = {
    'content-type': 'application/json',
    'Authorization': constant.firebaseTokenAPIFCM // 'key=YOUR_SERVER_KEY'
  };

  final response = await http.post(postUrl,
      body: json.encode(data),
      encoding: Encoding.getByName('utf-8'),
      headers: headers);

  if (response.statusCode == 200) {
    // on success do sth
    print('test ok push CFM');
    return true;
  } else {
    print(' CFM error');
    // on failure do sth
    return false;
  }
}

You can also check the post call from postman in order to make some tests. POST request On Headers add the:

  1. key Authorization with value key=AAAAO........ // Project Overview -> Cloud Messaging -> Server Key
  2. key Content-Type with value application/json

And on the body add

{
 "registration_ids" :[ "userUniqueToken1", "userUniqueToken2",... ],
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Test post",
     "title": "Push notifications E"
 }
}

"registration_ids" to send it to multiple tokens (same user logged in to more than on device at the same time) "to" in order to send it to a single token (one device per user / or update always the user token that is connected with his device and have 1 token ... 1 user)

I'm making an edit to the response, in order to add that is very important to add the FCM Server Key on a trusted environment or server!

这篇关于Flutter:如何使用 fcm 以编程方式发送推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆