我想有一个dart后台服务永远运行(隔离),它将通过websockets与服务器通信。我有一个Android API,它收集信息发送到服务器。我如何调用Android方法,它使用回调和后台隔离的一切?
- 编辑**
到目前为止,我在dart中创建了一个Isolate,用于定期在后台调用poolSong方法,即使用户正在使用另一个应用程序或屏幕已关闭。
但这给了我下面的错误...关于github的问题,他们说我不能从不同的隔离群发送平台消息,除非它是主隔离群。但如果我从主隔离群发送,当用户退出应用程序时,该隔离群也将终止。
主 dart
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
static const platform = const MethodChannel('mainService');
static _poolSong(SendPort sendPort) async {
const oneSec = const Duration(seconds:1);
new Timer.periodic(oneSec, (Timer t) => platform.invokeMethod('poolSong'));
}
@override
void initState() {
super.initState();
ReceivePort receivePort = ReceivePort();
Isolate.spawn(_poolSong, receivePort.sendPort);
}
·
·
·
主活动Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
(call, result) -> {
if (call.method.equals("startService"))
startService();
if (call.method.equals("poolSong"))
poolSong();
}
);
}
错误
E/flutter (25412): [ERROR:flutter/runtime/dart_isolate.cc(717)] Isolate (765499726) 'main.dart:_poolSong()' exited with an error
E/flutter (25412): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
E/flutter (25412): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
E/flutter (25412): #0 Window.sendPlatformMessage (dart:ui/window.dart:811:9)
E/flutter (25412): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:39:15)
E/flutter (25412): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:87:12)
E/flutter (25412): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:286:49)
E/flutter (25412): <asynchronous suspension>
E/flutter (25412): #4 _MyHomePageState._poolSong.<anonymous closure> (package:musictie/main.dart:37:54)
E/flutter (25412): #5 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
E/flutter (25412): #6 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
E/flutter (25412): #7 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
2条答案
按热度按时间pprl5pva1#
此错误发生时,尝试运行dart代码时,应用程序是在垃圾(应用程序关闭),到目前为止,处理后台服务的最佳方式是做你需要在本机代码,并不尝试运行任何从dart时,应用程序关闭.
fnx2tebb2#
由于Flutter 3.7插件和平台通道可用于任何分离菌株,而不仅仅是根分离菌株。
参考文献: