I'm very beginner in mobile development. I want to create an android app with flutter which send a GET request to my server every minutes even if the app is in background or screen is off. I did it with the Cron plugin but when the app is no more in foreground, the data are not sent to my server. Can you please help me to know which plugin need I to use ? I tried with android_workmanager_plus but periodically wasn't seem to work :/
this is how it's implemented for the moment
TextButton(
onPressed: () {
var cron = Cron();
cron.schedule(Schedule.parse('*/1 * * * *'), () async {
BlocProvider.of<TestCubit>(context).validate();
});
},
and this is my method in my cubit file
validate() async{
var battery = Battery();
var batlevel = await battery.batteryLevel;
state.status = Colors.blue;
emit(state);
try{
final batt = await repo.getBattery(batlevel.toString());
print(batt);
//print(state.path);
}catch(e){
print(e);
}
state.status = Colors.green;
emit(state);
}
}
Thanks for your future help :)
CodePudding user response:
You don't need any plugins to repeat something every second, however I doubt this works when the app is not open, it works when the app is open and backgrounded
t = Timer.periodic(Duration(seconds: 1), (Timer timer) => yourFunction());
CodePudding user response:
You can use dart:async
in your code with Timer.periodic
ex: for run task every 60 seconds
timer = Timer.periodic(
const Duration(
seconds: 60, //You can change second to milisecond etc
),
(t) => getData(),
);
you can add it in function or in initstate, Docs
Nb: don't forget to add
import 'dart:async';
and late Timer timer;