Flutter implements continuous activity after the app enters the background

In order to keep the Flutter app alive after it goes into the background, you can use the following method:

  1. Use the Flutter plug-in method to WidgetsBindingObservermonitor the life cycle changes of the application through . After the app goes into the background, use to Isolate.spawn()start a new detached Dart code executor, keeping the app running.

The specific implementation steps are as follows:

  1. Use to WidgetsBindingObservermonitor 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();
    }
  }

  // ...
}

  1. 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 Timerto 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 IsolateNameServercan . 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'));
}

  1. Use android_alarm_managerthe plugin in combination with flutter_isolatethe plugin to keep the app active while entering the background.

android_alarm_managerThe plugin can be used to AlarmManagerenable . And flutter_isolateplugins can assist in managing and creating slices and passing messages between slices.

The specific implementation steps are as follows:

  1. Add and dependency pubspec.yamlin :android_alarm_managerflutter_isolate
dependencies:
  flutter:
    sdk: flutter
  android_alarm_manager: ^0.5.4+3
  flutter_isolate: ^1.0.1

  1. Add Android project settings.

  2. 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 FlutterIsolateinitialize a new slice, then use to IsolateNameServerget sendPortand send messages, and finally use Timer.periodic()to simulate a piece of task logic.

  1. Create a new slice of Dart code in MyAppStatethe class and use android_alarm_managerto 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_managerthe and flutter_isolateplugins 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.
insert image description here
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

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
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↓↓↓

Guess you like

Origin blog.csdn.net/weixin_43440181/article/details/130602196