I have code to refresh data from server which I need to run even when screen is off. I tried to do this with an isolate:
static void isolateFunc(SendPort mainSendPort) async{
String _answer = "";
while(true){
Socket socket = await Socket.connect(ipAddress, port, timeout: Duration(seconds: 5));
socket.add(utf8.encode("connection test"));
socket.listen((List<int> event) {
_answer = utf8.decode(event);
});
socket.close();
await Future.delayed(Duration(seconds: 5));
}
}
This works fine when screen is on. But after switching off the screen it refreshs maybe for 5 times normally, then it refreshs for a few times each 30 sesconds(even when the delay is set to 5 seconds) and then it just stops. I am calling the isolate from initState like this:
@override
void initState() {
super.initState();
anotherRefresher();
ReceivePort recievePort = ReceivePort();
Isolate.spawn(isolateFunc, recievePort.sendPort);
}
Battery optimalisation in android settings is off. I do not understand this :/ Any ideas how to deal with this please?
After some time I found that, there is no way how to keep running dart code in the background without setting it as background or foreground process. Both Android and iOS will always restrict your code to increase battery life. Even turning off battery optimisation will not help. So to keep dart code running even when screen is off, you need to set up background or foreground process. For this you can do some platform native coding and connect it through platform channels or use plugins. Since I don't know Swift or Kotlin, I decided to find some plugins. I have tried more of them and after some time I can say that plugin flutter_background_service is one of the best. Or based on your needs you can find another plugins or try to code it by yourself. Wish you good luck :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With