flutter-监听application活动
flutter
中,除了了解组件生命周期
,有时候还会需要用到应用活动状态
,当我们需要观察应用状态做出某种行为时,那么就需要了解他了,例如:我们想在应用进入前台时,检测用户行为,那么就不可避免会用到
//使用时,类需要多继承子 WidgetsBindingObserver 类,多继承,因此用with
class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver
@override
void initState() {
//监听application生命周期
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void dispose() {
//组件销毁时,移除监听,否则不会主动移除
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
//应用状态变化后的回调
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.resumed) {
print("app进入前台");
} else if (state == AppLifecycleState.inactive) {
print("app在前台但不响应事件,比如电话,touch id等");
} else if (state == AppLifecycleState.paused) {
print("app进入后台");
} else if (state == AppLifecycleState.detached) {
print("没有宿主视图但是flutter引擎仍然有效");
}
}
转载自:https://juejin.cn/post/7087251528754397197