I try to run app in background to detect inclination of device.
To do this I ear that I need to use isolate. I test a code with isolate and add my logic to detect vertical angle. It's work but only 20seconds on my iphone.
How can I run a simple accelerometer continually in background ?
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_isolate/flutter_isolate.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sensors/sensors.dart';
void isolate2(String arg) {
getTemporaryDirectory().then((dir) {
print("isolate2 temporary directory: $dir");
});
Timer.periodic(
Duration(seconds: 1), (timer) => print("Timer Running From Isolate 2"));
}
void isolate1(String arg) async {
/*final isolate =*/ await FlutterIsolate.spawn(isolate2, "text2");
getTemporaryDirectory().then((dir) {
print("isolate1 temporary directory: $dir");
});
Timer.periodic(
Duration(seconds: 1), (timer) => print("Timer Running From Isolate 1"));
}
void main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<void> _run() async {
final isolate = await FlutterIsolate.spawn(isolate1, "text1");
accelerometerEvents.listen((AccelerometerEvent event) {
print(event.y);
if (event.y>5.0||event.y<-5.0){
print("vertical detection");
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: ElevatedButton(
child: Text('Run'),
onPressed: _run,
),
),
),
);
}
}
thank you