Flutter应用生命周期管理插件app_life的使用
Flutter应用生命周期管理插件app_life的使用
原生的生命周期函数,支持 iOS 和 Android,不同于 flutter 中自带的 WidgetBindings
Android/IOS 原生生命周期
android 生命周期
ON_CREATE
onCreateON_START
onStartON_RESTART
onRestartON_RESUME
onResumeON_STOP
onStopON_PAUSE
onPauseON_DESTROY
onDestroy
iOS 生命周期
DID_FINISH_LAUNCHING_WITH_OPTIONS
didFinishLaunchingWithOptionsAPPLICATION_WILL_RESIGN_ACTIVE
applicationWillResignActiveAPPLICATION_DID_ENTER_BACKGROUND
applicationDidEnterBackgroundAPPLICATION_WILL_ENTER_FOREGROUND
applicationWillEnterForegroundAPPLICATION_DID_BECOME_ACTIVE
applicationDidBecomeActiveAPPLICATION_WILL_TERMINATE
applicationWillTerminate
注册生命周期函数
Android
public class MainActivity extends FlutterActivity {
private static final String TAG = MainActivity.class.getName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 注册对应的生命周期函数
AppLifeManage.registerLife(AppLifeManage.LifeEnum.ON_CREATE);
Log.e(TAG, "onCreate: ");
}
@Override
protected void onRestart() {
super.onRestart();
Log.e(TAG, "onRestart: ");
AppLifeManage.registerLife(AppLifeManage.LifeEnum.ON_RESTART);
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume: ");
AppLifeManage.registerLife(AppLifeManage.LifeEnum.ON_RESUME);
}
}
iOS
- 引入头文件
#import "AppLifePlugin.h"
@implementation AppDelegate
/**
应用创建
*/
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Override point for customization after application launch.
NSLog(@"%@", @"didFinishLaunchingWithOptions: 应用创建");
[AppLifePlugin registerLife:DID_FINISH_LAUNCHING_WITH_OPTIONS];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
/**
应用从活动状态进入非活动状态,如从应用切换到桌面
*/
- (void)applicationWillResignActive:(UIApplication *)application{
NSLog(@"%@", @"applicationWillResignActive: 应用从活动状态进入非活动状态");
[AppLifePlugin registerLife:APPLICATION_WILL_RESIGN_ACTIVE];
}
/**
应用处于后台
*/
- (void)applicationDidEnterBackground:(UIApplication *)application{
NSLog(@"%@", @"applicationDidEnterBackground: 应用处于后台");
[AppLifePlugin registerLife:APPLICATION_DID_ENTER_BACKGROUND];
}
/**
应用进入前台,但还没有处于活动状态
*/
- (void)applicationWillEnterForeground:(UIApplication *)application{
NSLog(@"%@", @"applicationWillEnterForeground: 应用进入前台,但还没有处于活动状态");
[AppLifePlugin registerLife:APPLICATION_WILL_ENTER_FOREGROUND];
}
/**
应用处于前台并且活动状态
*/
- (void)applicationDidBecomeActive:(UIApplication *)application{
NSLog(@"%@", @"applicationDidBecomeActive: 应用处于前台并且活动状态");
[AppLifePlugin registerLife:APPLICATION_DID_BECOME_ACTIVE];
}
/**
应用终止,销毁
*/
- (void)applicationWillTerminate:(UIApplication *)application{
NSLog(@"%@", @"applicationWillTerminate: 应用终止,销毁");
[AppLifePlugin registerLife:APPLICATION_WILL_TERMINATE];
}
@end
Flutter
- 使用
with LifeManageCall
- 在
initState
方法中添加观察者
class WithTestPage extends StatefulWidget {
const WithTestPage({Key? key}) : super(key: key);
[@override](/user/override)
_WithTestPageState createState() => _WithTestPageState();
}
class _WithTestPageState extends State<WithTestPage> with LifeManageCall {
[@override](/user/override)
void initState() {
super.initState();
LifeManage.instance!.addObserver(this);
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('WithTest'),
),
body: Center(
child: Column(),
));
}
[@override](/user/override)
void onCreate() {
print("onCreate=============");
}
[@override](/user/override)
void onRestart() {
print("onRestart=============");
}
[@override](/user/override)
void applicationDidBecomeActive() {
print("applicationDidBecomeActive=============");
}
[@override](/user/override)
void applicationDidEnterBackground() {
print("applicationDidEnterBackground=============");
}
}
完整示例Demo
example/lib/main.dart
import 'package:app_life_example/with_test.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
[@override](/user/override)
void initState() {
super.initState();
}
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(home: WithTestPage());
}
}
更多关于Flutter应用生命周期管理插件app_life的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter应用生命周期管理插件app_life的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中,应用生命周期管理是一个重要的方面,尤其是在需要根据应用的状态(如前台、后台、暂停等)执行特定操作时。Flutter 提供了 WidgetsBindingObserver
来监听应用的生命周期事件,但为了更方便地管理生命周期,可以使用第三方插件 app_life
。
app_life
插件提供了一个简单的方式来监听应用的生命周期状态变化。以下是使用 app_life
插件的步骤:
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 app_life
插件的依赖:
dependencies:
flutter:
sdk: flutter
app_life: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 初始化 AppLife
在你的 main.dart
文件中,初始化 AppLife
:
import 'package:flutter/material.dart';
import 'package:app_life/app_life.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'AppLife Demo',
home: AppLifeWrapper(
child: MyHomePage(),
),
);
}
}
3. 使用 AppLife
监听生命周期
你可以在任何 widget 中使用 AppLife
来监听应用的生命周期状态变化。以下是一个示例:
import 'package:flutter/material.dart';
import 'package:app_life/app_life.dart';
class MyHomePage extends StatefulWidget {
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with AppLifecycleMixin {
[@override](/user/override)
void initState() {
super.initState();
appLife.addListener(_onAppLifecycleChanged);
}
[@override](/user/override)
void dispose() {
appLife.removeListener(_onAppLifecycleChanged);
super.dispose();
}
void _onAppLifecycleChanged(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print('App resumed');
break;
case AppLifecycleState.inactive:
print('App inactive');
break;
case AppLifecycleState.paused:
print('App paused');
break;
case AppLifecycleState.detached:
print('App detached');
break;
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AppLife Demo'),
),
body: Center(
child: Text('Check the console for lifecycle events'),
),
);
}
}