0

我实际上正在使用电子商务应用程序,并希望在从用户应用程序下订单时向送货员发送通知。我们如何从背景中识别特定的送货员应用程序(当应用程序退出时)。

 Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage 
   message) async {
  await Firebase.initializeApp();
 SharedPreferences _prefs = await SharedPreferences.getInstance();
 
     print('A message just showed : ${message.messageId}');
 
  } 



 void main() async {
 WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// <------------Local Notification Initilization-------------->

 FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
 await flutterLocalNotificationsPlugin
  .resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
  ?.createNotificationChannel(channel);

    runApp(MyApp());
 }
4

1 回答 1

0

使用 http 请求发送通知,并使用 topic 参数进行特定用户选择,检查我在我的案例中使用的代码示例:

final String serverToken = 'YOUR_SERVER_TOKEN_HERE';
  FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;

  Future<Map<String, dynamic>> sendAndRetrieveMessage(String typeOfNotification, 
  {String? sellerId, String? chatId, String? postId}) async {
    NotificationSettings settings = await firebaseMessaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
    String notification = getNotificationMessage(typeOfNotification);

    notificationMsg.value = notification;
    addToNotifications(sellerId!, notification, postId ?? "$userId", chatId ?? "$userId");
    print('User granted permission: ${settings.authorizationStatus}');

    String topic = '';

    if (typeOfNotification == 'live') {
      topic = "/topics/$userId";
    } else if (typeOfNotification == 'post') {
      topic = "/topics/$userId";
    } else {
      topic = "/topics/${sellerId}_personal";
    }

    await http.post(
      Uri.parse('https://fcm.googleapis.com/fcm/send'),
      headers: <String, String>{
        'Content-Type': 'application/json',
        'Authorization': 'key=$serverToken',
      },
      body: jsonEncode(
        <String, dynamic>{
          'notification': <String, dynamic>{
            'body': "${userIsASeller.value ? shopName.value : userName.value} $notification",
            'title': "Shopenlive",
          },
          'priority': 'high',
          'data': <String, dynamic>{
            'click_action': 'FLUTTER_NOTIFICATION_CLICK',
            'id': '1',
            'status': 'done',
            'title': "Shopenlive",
            'body': "${userIsASeller.value ? shopName.value : userName.value} $notification",
          },
          'to': topic,
        },
      ),
    );

    final Completer<Map<String, dynamic>> completer = Completer<Map<String, dynamic>>();

    /* firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        completer.complete(message);
      },
    ); */

    return completer.future;
  }

于 2022-02-21T10:23:10.903 回答