Reputation: 1219
Is there a way to detect when the app has been minimized? Simply using WidgetsBindingObserver
with the paused
event doesn't work as it's indistinguishable from when the user turns off the screen / phone locks. Note, I need this to work for both android and ios.
A bit of context of what I'm doing. In the application, I'm running a timer. I want to stop this timer if the user minimizes the app (e.g. uses its phone for something else). If the user, however, turns off the screen/locks it, I want the timer to continue.
Upvotes: 8
Views: 7555
Reputation: 671
Above solution is also good but if you prefer not to import any library.
You just simply need to observe
your WidgetBinding
in initial screen and listen it.
Include abstract class WidgetsBindingObserver
in your initial screen like splash screen:
class _SplashState extends State<Splash> with WidgetsBindingObserver {
Implement Observer in initState
to observer app state:
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
and then finally track app lifecycle by this method
void didChangeAppLifecycleState(AppLifecycleState state) async {
switch (state) {
case AppLifecycleState.resumed:
print('Back to app');
break;
case AppLifecycleState.paused:
print('App minimised or Screen locked');
break;
}
}
Upvotes: 5
Reputation: 3290
I suggest to take a look at this package: is_lock_screen
As the description suggest
Useful for determining whether app entered background due to locking screen or leaving app.
I would try with this:
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.inactive) {
final isLock = await isLockScreen();
if(!isLock){
print('app inactive MINIMIZED!');
}
print('app inactive in lock screen!');
} else if (state == AppLifecycleState.resumed) {
print('app resumed');
}
}
Upvotes: 6