In order to keep the Flutter app alive after it goes into the background, you can use the following method:
- Use the Flutter plug-in method to
WidgetsBindingObserver
monitor the life cycle changes of the application through . After the app goes into the background, use toIsolate.spawn()
start a new detached Dart code executor, keeping the app running.
The specific implementation steps are as follows:
- Use to
WidgetsBindingObserver
monitor lifecycle changes:
class MyAppState extends State<MyApp> with WidgetsBindingObserver {
// ...
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.paused) {
startIsolate();
}
}
// ...
}
- Start a new Dart code executor in
startIsolate()
the method :
void startIsolate() {
IsolateNameServer.registerPortWithName(
_backgroundChannelName, SendPort.receivePort);
if (_isolate == null) {
Isolate.spawn(backgroundTask, SendPort.receivePort);
}
}
void backgroundTask(SendPort sendPort) async {
final timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
print('background task running');
});
sendPort?.send(null); // dummy message
}
In the above code, startIsolate()
the method starts a new detached Dart code executor and runs the task backgroundTask()
named . The task simply uses backgroundTask()
in Timer
to periodically output a log message.
It should be noted that there is no way to share data between the separate code executor started by the above code and the main thread of the application, but a channel IsolateNameServer
can . That is MyAppState
, initState()
in the method of , you can add the following piece of code to connect with each other:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
IsolateNameServer.registerPortWithName(ui.window.onReportTimings,
'com.example.isolatesample.performance')
.then((_) => print('Registered port'));
IsolateNameServer.registerPortWithName(_backgroundChannelName,
IsolateNameServer.lookupPortByName(_backgroundChannelName))
.then((_) => print('Registered $_backgroundChannelName'));
}
- Use
android_alarm_manager
the plugin in combination withflutter_isolate
the plugin to keep the app active while entering the background.
android_alarm_manager
The plugin can be used to AlarmManager
enable . And flutter_isolate
plugins can assist in managing and creating slices and passing messages between slices.
The specific implementation steps are as follows:
- Add and dependency
pubspec.yaml
in :android_alarm_manager
flutter_isolate
dependencies:
flutter:
sdk: flutter
android_alarm_manager: ^0.5.4+3
flutter_isolate: ^1.0.1
-
Add Android project settings.
-
Create a new slice Dart code file in which to write the specific task logic.
class ExecutionMessage {
final int id;
ExecutionMessage(this.id);
}
void main() async {
final FlutterIsolate isolate = FlutterIsolate(getTask, name: 'BackgroundIsolate');
}
Future<void> getTask() async {
print('BackgroundIsolate: Starting task...');
final SendPort mainSendPort = IsolateNameServer.lookupPortByName(_isolateName)!;
final ExecutionMessage message = const ExecutionMessage(42);
Timer.periodic(Duration(seconds: 1), (_) {
mainSendPort.send(message);
print('BackgroundIsolate: Sent message $message');
});
}
In this slice processing code file, first use to FlutterIsolate
initialize a new slice, then use to IsolateNameServer
get sendPort
and send messages, and finally use Timer.periodic()
to simulate a piece of task logic.
- Create a new slice of Dart code in
MyAppState
the class and useandroid_alarm_manager
to set a timer and start the task.
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter_isolate/flutter_isolate.dart';
class MyAppState extends State<MyApp> with WidgetsBindingObserver {
late final FlutterIsolate _isolate;
static const String _isolateName = 'isolate';
Future<void> _initializeAlarm() async {
await AndroidAlarmManager.initialize();
await AndroidAlarmManager.oneShot(Duration(seconds: 5), 0, executeTask,
allowWhileIdle: true, wakeup: true);
}
Future<void> executeTask() async {
final SendPort mainSendPort = IsolateNameServer.lookupPortByName(_isolateName)!;
final ExecutionMessage message = const ExecutionMessage(42);
Timer.periodic(Duration(seconds: 1), (_) {
mainSendPort.send(message);
print('BackgroundIsolate: Sent message $message');
});
}
//...
}
Here, first ensure that android_alarm_manager
the and flutter_isolate
plugins are initialized, then use AndroidAlarmManager.oneShot()
to set up a timed task, and _executeTask()
execute the logic in the method.
After starting the application and entering the background for a period of time, you should be able to see log information similar to the following in the console:
I/flutter (22731): BackgroundIsolate: Sent message Instance of 'ExecutionMessage'
at last
If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.
If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.
Full set of video materials:
1. Interview collection
2. Source code analysis collection
3. The collection of open source frameworks
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓