【问题标题】:run dart code in the background even when my app is closed即使我的应用程序关闭,也会在后台运行 dart 代码
【发布时间】:2020-05-22 22:03:15
【问题描述】:

在颤振中,我使用adhara_socket_io 打开一个套接字并从我的服务器接收数据以使用flutter_local_notifications 推送通知,它在应用程序运行时工作,现在我需要让它在后台运行所以当我的应用程序没有运行时,它仍然从我的服务器接收数据并推送通知,无论如何在颤振中这样做吗?

   void initSocket() async {
    final deviceInfo = await Constants.getDeviceDetails();
    final String deviceId = deviceInfo[2];
    Uuid uuid = Uuid();
    print(deviceInfo);
    final id = uuid.v5(Uuid.NAMESPACE_URL, deviceId);
    print('id ' + id);

    SocketIOManager manager = SocketIOManager();
    SocketIO socket = await manager.createInstance(
      SocketOptions(URI,
          enableLogging: false,
          transports: [Transports.WEB_SOCKET /*, Transports.POLLING*/]),
    );
    socket.onConnect((data) {
      print("connected...");
      print(data);
      socket.emit('settings', [
        {'device_id': id}
      ]);
    });
    socket.onConnectError((_) => print('connect error'));
    socket.onConnectTimeout((_) => print('timeout'));
    socket.onError((_) => print('error'));
    socket.onDisconnect((_) => print('disconnect'));
    socket.on('notif', (data) {
      print('notif');
      _showNotificationWithDefaultSound(data['heading'],data['content']);
    });
    socket.connect();
  }

  initNotifications() {
    var initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = IOSInitializationSettings();
    var initializationSettings = InitializationSettings(initializationSettingsAndroid,initializationSettingsIOS);
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    flutterLocalNotificationsPlugin.initialize(initializationSettings,onSelectNotification: onSelectNotification);
  }

  Future onSelectNotification(String payload)async{
    print('payload');
  }

  Future _showNotificationWithDefaultSound(heading,content) async {
  var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'your channel id', 'your channel name', 'your channel description',
      importance: Importance.Max, priority: Priority.High);
  var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
  var platformChannelSpecifics = new NotificationDetails(
      androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
  await flutterLocalNotificationsPlugin.show(
    0,
    heading,
    content,
    platformChannelSpecifics,
    payload: 'Default_Sound',
  );
}

【问题讨论】:

    标签: flutter dart service socket.io background


    【解决方案1】:

    https://medium.com/vrt-digital-studio/flutter-workmanager-81e0cfbd6f6e
    希望这会有所帮助,或者你可以使用 fcm https://fireship.io/lessons/flutter-push-notifications-fcm-guide/

    但是我是初学者。我对此了解不多。如果这对您没有帮助,请见谅。

    【讨论】:

    • 我认为只要你连接到互联网它就可以工作
    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多