2024-03-01 18:22:57 +00:00
|
|
|
import 'dart:collection';
|
2023-10-20 23:12:33 +00:00
|
|
|
import 'dart:isolate';
|
|
|
|
|
|
|
|
import 'package:flutter_background_service/flutter_background_service.dart';
|
|
|
|
|
2024-03-01 18:22:57 +00:00
|
|
|
typedef ListenerCallback = void Function(Map<String, dynamic>? args);
|
|
|
|
|
2023-10-20 23:12:33 +00:00
|
|
|
class ServiceInterface {
|
|
|
|
final ReceivePort? receivePort;
|
2024-03-01 18:22:57 +00:00
|
|
|
late SendPort sendPort;
|
2023-10-20 23:12:33 +00:00
|
|
|
final ServiceInstance? service;
|
|
|
|
|
2024-03-01 18:22:57 +00:00
|
|
|
bool _isListening = false;
|
|
|
|
final _listeners = HashMap<String, ListenerCallback>();
|
|
|
|
|
2023-10-20 23:12:33 +00:00
|
|
|
ServiceInterface({this.receivePort, this.service})
|
|
|
|
: assert(receivePort != null || service != null);
|
|
|
|
|
2024-03-01 18:22:57 +00:00
|
|
|
void on(String method, ListenerCallback listener) {
|
|
|
|
if (service != null) {
|
|
|
|
service!.on(method).listen(listener);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!_isListening) {
|
|
|
|
_isListening = true;
|
|
|
|
receivePort!.listen((message) {
|
|
|
|
final method = message['_'];
|
|
|
|
_listeners[method]!.call(message);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
_listeners[method] = listener;
|
|
|
|
}
|
|
|
|
|
|
|
|
void no(String method) {
|
|
|
|
_listeners.remove(method);
|
|
|
|
}
|
|
|
|
|
|
|
|
void send(String method, [Map<String, dynamic>? args]) {
|
2023-10-20 23:12:33 +00:00
|
|
|
if (service != null) {
|
2024-03-01 18:22:57 +00:00
|
|
|
return service!.invoke(method, args);
|
2023-10-20 23:12:33 +00:00
|
|
|
}
|
|
|
|
|
2024-03-01 18:22:57 +00:00
|
|
|
sendPort!.send({'_': method, if (args != null) ...args});
|
2023-10-20 23:12:33 +00:00
|
|
|
}
|
|
|
|
}
|