Flutter 在后台运行 websocket?

Nic*_*ela 10 dart flutter

我已经编写了一个基于 websocket 的应用程序,但是当我回到家(iOS 和 Android)时,websocket 不再工作了。如何让 websocket 仍然在后台工作?使服务可以一直运行。这是我的流和订阅:

channel = new IOWebSocketChannel.connect(wsUrl);
      globalChannel = channel;
      print("web socket channel connected.");

      // add channel.stream to streamController
      setState(() {
        _streamController = StreamController.broadcast();
        _streamController.addStream(channel.stream);
        globalStreamController = _streamController;
      });

      // Here we listen to ws stream and add to global messages
      // when enter chat page, globalSubscription should be stop
      // if globalSub were canceled, how to reopen it??
      globalSubscription = globalStreamController.stream.listen((data) {
}
Run Code Online (Sandbox Code Playgroud)

如何让这个流控制器仍然运行而不是在当前页面类中受到限制?

Dan*_*eny 6

关于 SO 和网络的其他答案表明,您不能只在后台保持套接字打开(这似乎合理,您会保持打开的网络连接,这可能会影响电池寿命)。根据您的用例,您可能最好查看推送通知或按计划检查的内容。