我想检测我的iOS应用写入时是否颤抖地移至背景并进入前景。我曾经习惯 WidgetsBindingObserver 来听一听扑扑的生命周期。但这完全不符合我的期望。当我在浮动应用程序生命周期中推送本机控制器时,触发 AppLifecycleState.paused ,但我的应用程序正在运行。有人遇到过这个问题吗?以及您解决问题的方式。谢谢
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if(state == AppLifecycleState.paused) {
_viewModel.applicationMoveToBackground();
} else if(state == AppLifecycleState.resumed) {
_viewModel.applicationMoveToForeground();
}
}
答案 0 :(得分:1)
您是否正在使用WidgetsBindingObserver?
class _PageState extends State<Page> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if(state == AppLifecycleState.paused) {
_viewModel.applicationMoveToBackground();
} else if(state == AppLifecycleState.resumed) {
_viewModel.applicationMoveToForeground();
}
}
}
答案 1 :(得分:0)
我通过FlutterBasicMessageChannel的变通方法解决了这个问题,以发出iOS UIApplication 生命周期。 在iOS Runner应用程序中:
import UIKit
import Flutter
@UIApplicationMain@objc class AppDelegate: FlutterAppDelegate {
var applicationLifeCycleChannel: FlutterBasicMessageChannel!
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
GeneratedPluginRegistrant.register(with: self)
applicationLifeCycleChannel = FlutterBasicMessageChannel(
name: "applicationLifeCycle",
binaryMessenger: (window.rootViewController as! FlutterViewController).binaryMessenger,
codec: FlutterStringCodec.sharedInstance())
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func applicationWillTerminate(_ application: UIApplication) {
applicationLifeCycleChannel.sendMessage("applicationWillTerminate")
}
override func applicationWillEnterForeground(_ application: UIApplication) {
applicationLifeCycleChannel.sendMessage("applicationWillEnterForeground")
}
override func applicationDidEnterBackground(_ application: UIApplication) {
applicationLifeCycleChannel.sendMessage("applicationDidEnterBackground")
}
}
在Flutter应用中:
static const applicationLifecycleChannel = BasicMessageChannel<String>('applicationLifeCycle', StringCodec());
static const kApplicationWillTerminate = 'applicationWillTerminate';
static const kApplicationWillEnterForeground = 'applicationWillEnterForeground';
static const kApplicationDidEnterBackground = 'applicationDidEnterBackground';
@override
void initState() {
applicationLifecycleChannel.setMessageHandler((message) async {
switch(message) {
case kApplicationWillTerminate:
break;
case kApplicationWillEnterForeground:
_viewModel.applicationMoveToForeground();
break;
case kApplicationDidEnterBackground:
_viewModel.applicationMoveToBackground();
break;
default:
break;
}
return message;
});
super.initState();
}