Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/220.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android FCM仅在应用程序被终止时在托盘中发送消息,但我需要声音通知_Android_Firebase_Flutter_Dart_Firebase Cloud Messaging - Fatal编程技术网

Android FCM仅在应用程序被终止时在托盘中发送消息,但我需要声音通知

Android FCM仅在应用程序被终止时在托盘中发送消息,但我需要声音通知,android,firebase,flutter,dart,firebase-cloud-messaging,Android,Firebase,Flutter,Dart,Firebase Cloud Messaging,我使用的是一个简单的firebase消息示例,该示例来自firebase_消息包的示例部分 主飞镖 import 'dart:async'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; final Map<String, Item> _items = <String, Item>{}; Item _itemFor

我使用的是一个简单的firebase消息示例,该示例来自firebase_消息包的示例部分

主飞镖

import 'dart:async';

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

final Map<String, Item> _items = <String, Item>{};
Item _itemForMessage(Map<String, dynamic> message) {
  final dynamic data = message['data'] ?? message;
  final String itemId = data['id'];
  final Item item = _items.putIfAbsent(itemId, () => Item(itemId: itemId))
    ..status = data['status'];
  return item;
}

class Item {
  Item({this.itemId});
  final String itemId;

  StreamController<Item> _controller = StreamController<Item>.broadcast();
  Stream<Item> get onChanged => _controller.stream;

  String _status;
  String get status => _status;
  set status(String value) {
    _status = value;
    _controller.add(this);
  }

  static final Map<String, Route<void>> routes = <String, Route<void>>{};
  Route<void> get route {
    final String routeName = '/detail/$itemId';
    return routes.putIfAbsent(
      routeName,
      () => MaterialPageRoute<void>(
        settings: RouteSettings(name: routeName),
        builder: (BuildContext context) => DetailPage(itemId),
      ),
    );
  }
}

class DetailPage extends StatefulWidget {
  DetailPage(this.itemId);
  final String itemId;
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  Item _item;
  StreamSubscription<Item> _subscription;

  @override
  void initState() {
    super.initState();
    _item = _items[widget.itemId];
    _subscription = _item.onChanged.listen((Item item) {
      if (!mounted) {
        _subscription.cancel();
      } else {
        setState(() {
          _item = item;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Item ${_item.itemId}"),
      ),
      body: Material(
        child: Center(child: Text("Item status: ${_item.status}")),
      ),
    );
  }
}

class PushMessagingExample extends StatefulWidget {
  @override
  _PushMessagingExampleState createState() => _PushMessagingExampleState();
}

class _PushMessagingExampleState extends State<PushMessagingExample> {
  String _homeScreenText = "Waiting for token...";
  bool _topicButtonsDisabled = false;

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final TextEditingController _topicController =
      TextEditingController(text: 'topic');

  Widget _buildDialog(BuildContext context, Item item) {
    return AlertDialog(
      content: Text("Item ${item.itemId} has been updated"),
      actions: <Widget>[
        FlatButton(
          child: const Text('CLOSE'),
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
        FlatButton(
          child: const Text('SHOW'),
          onPressed: () {
            Navigator.pop(context, true);
          },
        ),
      ],
    );
  }

  void _showItemDialog(Map<String, dynamic> message) {
    showDialog<bool>(
      context: context,
      builder: (_) => _buildDialog(context, _itemForMessage(message)),
    ).then((bool shouldNavigate) {
      if (shouldNavigate == true) {
        _navigateToItemDetail(message);
      }
    });
  }

  void _navigateToItemDetail(Map<String, dynamic> message) {
    final Item item = _itemForMessage(message);
    // Clear away dialogs
    Navigator.popUntil(context, (Route<dynamic> route) => route is PageRoute);
    if (!item.route.isCurrent) {
      Navigator.push(context, item.route);
    }
  }

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        _showItemDialog(message);
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        _navigateToItemDetail(message);
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        _navigateToItemDetail(message);
      },
    );
    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(
            sound: true, badge: true, alert: true, provisional: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      setState(() {
        _homeScreenText = "Push Messaging token: $token";
      });
      print(_homeScreenText);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Push Messaging Demo'),
        ),
        // For testing -- simulate a message being received
        floatingActionButton: FloatingActionButton(
          onPressed: () => _showItemDialog(<String, dynamic>{
            "data": <String, String>{
              "id": "2",
              "status": "out of stock",
            },
          }),
          tooltip: 'Simulate Message',
          child: const Icon(Icons.message),
        ),
        body: Material(
          child: Column(
            children: <Widget>[
              Center(
                child: Text(_homeScreenText),
              ),
              Row(children: <Widget>[
                Expanded(
                  child: TextField(
                      controller: _topicController,
                      onChanged: (String v) {
                        setState(() {
                          _topicButtonsDisabled = v.isEmpty;
                        });
                      }),
                ),
                FlatButton(
                  child: const Text("subscribe"),
                  onPressed: _topicButtonsDisabled
                      ? null
                      : () {
                          _firebaseMessaging
                              .subscribeToTopic(_topicController.text);
                          _clearTopicText();
                        },
                ),
                FlatButton(
                  child: const Text("unsubscribe"),
                  onPressed: _topicButtonsDisabled
                      ? null
                      : () {
                          _firebaseMessaging
                              .unsubscribeFromTopic(_topicController.text);
                          _clearTopicText();
                        },
                ),


----------


              ])
            ],
          ),
        ));
  }

  void _clearTopicText() {
    setState(() {
      _topicController.text = "";
      _topicButtonsDisabled = true;
    });
  }
}

void main() {
  runApp(
    MaterialApp(
      home: PushMessagingExample(),
    ),
  );
}

导入'dart:async';
导入“package:firebase_messaging/firebase_messaging.dart”;
进口“包装:颤振/材料.省道”;
最终地图_项={};
Item\u ItemFormMessage(映射消息){
最终动态数据=消息['data']??消息;
最终字符串itemId=data['id'];
最终项Item=\u items.putIfAbsent(itemId,()=>Item(itemId:itemId))
..状态=数据[‘状态’];
退货项目;
}
类项目{
项({this.itemId});
最终字符串itemId;
StreamController _controller=StreamController.broadcast();
Stream get onChanged=>\u controller.Stream;
字符串状态;
字符串get status=>\u status;
设置状态(字符串值){
_状态=价值;
_控制器。添加(此);
}
静态最终地图路线={};
路线得到路线{
最终字符串routeName='/detail/$itemId';
返回路线。putIfAbsent(
罗特奈,
()=>材料路线(
设置:路由设置(名称:routeName),
生成器:(BuildContext上下文)=>DetailPage(itemId),
),
);
}
}
类DetailPage扩展StatefulWidget{
DetailPage(此.itemId);
最终字符串itemId;
@凌驾
_DetailPageState createState()=>\u DetailPageState();
}
类_DetailPageState扩展状态{
项目(u)项目;;
流动认购(流动认购);;
@凌驾
void initState(){
super.initState();
_item=_items[widget.itemId];
_订阅=_item.onChanged.listen((item){
如果(!已安装){
_订阅。取消();
}否则{
设置状态(){
_项目=项目;
});
}
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“Item${{u Item.itemId}”),
),
主体:材料(
子项:中心(子项:文本(“项状态:${u Item.status}”),
),
);
}
}
类PushMessagineXample扩展StatefulWidget{
@凌驾
_PushMessagineXampleState createState()=>\u PushMessagineXampleState();
}
类_pushMessagineXampleState扩展状态{
字符串_homescrentext=“等待令牌…”;
bool\u topicButtonsDisabled=假;
最终FirebaseMessaging_FirebaseMessaging=FirebaseMessaging();
最终文本编辑控制器\u topicController=
TextEditingController(文本:“主题”);
小部件构建对话框(构建上下文,项目){
返回警报对话框(
内容:文本(“Item${Item.itemId}已更新”),
行动:[
扁平按钮(
子项:const Text('CLOSE'),
已按下:(){
pop(上下文,false);
},
),
扁平按钮(
子项:常量文本('SHOW'),
已按下:(){
pop(上下文,true);
},
),
],
);
}
void\u showItemDialog(映射消息){
显示对话框(
上下文:上下文,
生成器:()=>buildDialog(上下文,ItemFormMessage(消息)),
).然后((布尔应该导航){
if(shouldNavigate==true){
_导航项目详细信息(消息);
}
});
}
void _navigateToItemDetail(地图消息){
最终项目=_itemForMessage(消息);
//清除对话框
Navigator.popintil(context,(Route-Route)=>Route是PageRoute);
如果(!item.route.isCurrent){
推送(上下文、项、路线);
}
}
@凌驾
void initState(){
super.initState();
_firebaseMessaging.configure(
onMessage:(映射消息)异步{
打印(“onMessage:$message”);
_showItemDialog(消息);
},
onLaunch:(映射消息)异步{
打印(“onLaunch:$message”);
_导航项目详细信息(消息);
},
onResume:(映射消息)异步{
打印(“onResume:$message”);
_导航项目详细信息(消息);
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(
声音:真,徽章:真,警报:真,临时:真);
_firebaseMessaging.onissettings已注册
.listen((IONotificationSettings){
打印(“已注册设置:$Settings”);
});
_firebaseMessaging.getToken().then((字符串标记){
断言(令牌!=null);
设置状态(){
_homeScreenText=“推送消息传递令牌:$token”;
});
打印(_homeScreenText);
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:const Text(“推送消息演示”),
),
//用于测试——模拟正在接收的消息
浮动操作按钮:浮动操作按钮(
按下:()=>\u显示项目对话框({
“数据”:{
“id”:“2”,
“状态”:“缺货”,
},
}),
工具提示:“模拟消息”,
子:常量图标(Icons.message),
),
主体:材料(
子:列(
儿童:[
居中(
子:文本(_homeScreenText),
),
世界其他地区(儿童:[
扩大(
孩子:TextField(
控制器:_topicController,
一旦更改:(字符串v){
设置状态(){
_topicButtonsDisabled=v.isEmpty;
});
}),
),
扁平按钮(
子项:常量文本(“订阅”),
按下:主题按钮已禁用
无效的
: () {
_firebaseMessaging
.subscribeTopic(_topicController.text);
_clearTopicText();
},
),
扁平按钮(
芝加哥
<string name="notification_channel_id" translatable="false">my_unique_fcm_id</string>
<string name="notification_channel_name">The name of this notification</string>
<string name="notification_channel_desc">A description of the notification.</string>
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
     val channelID = getString(R.string.notification_channel_id)
     val name = getString(R.string.notification_channel_name)
     val descriptionText = getString(R.string.notification_channel_desc)
     val importance = NotificationManager.IMPORTANCE_HIGH
     val channel = NotificationChannel(channelID, name, importance).apply {
          description = descriptionText
      }
      // Register the channel with the system
      val notificationManager: NotificationManager =
           getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
      notificationManager.createNotificationChannel(channel)
}
val importance = NotificationManager.IMPORTANCE_HIGH
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/notification_channel_id" />