3
votes

There is a particular feature of this application, called Forest, I would like to emulate. Basically you start a timer in the application and you are not to switch out from it. This timer counts down if the application is in the foreground and/or when the screen is off.

There is a given grace period of approximately 10 seconds where a user can switch out of the app (i.e. press home button). If they do not return within the grace period, the timer ends and the user fails. Else the timer continues counting.

Basically the application has to check if it is the background. If it is, start a 10 second timer. Once this timer expire, set a bit such then when the app is back to foreground, the user continues/fails.

I am unsure how do this as reading the Flutter/Dart documentation, the lifecycle states available in Flutter is abstracted away from us. Would I have to run some background code or trigger an interrupt? I looked at the plugins available but they do not allow for triggers below 15 minutes. How is this achieved in native Android/iOS code?

1

1 Answers

2
votes

You can use Android alarm manager. Through which you can run some background task when alarm triggered.

import 'package:android_alarm_manager/android_alarm_manager.dart';

void printHello() {
  final DateTime now = new DateTime.now();
  final int isolateId = Isolate.current.hashCode;
  print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
}

main() async {
  final int helloAlarmID = 0;
  runApp(...);
  await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello);
}

prints 'Hello world' for every minute roughly even if app ends. PS: example code provided above was taken from plugin example.