即使关闭屏幕,如何在后台运行代码?

Lok*_*man 37 android flutter

我在Flutter中有一个简单的计时器应用程序,它显示剩余秒数的倒计时.我有:

new Timer.periodic(new Duration(seconds: 1), _decrementCounter);
Run Code Online (Sandbox Code Playgroud)

它似乎工作正常,直到我的手机显示屏关闭(即使我切换到另一个应用程序)并进入睡眠状态.然后,计时器暂停.是否有建议的方法来创建即使在屏幕关闭时在后台运行的服务?

Eri*_*del 29

回答如何实现特定计时器案例的问题实际上与背景代码无关.后台的整体运行代码在移动操作系统上是不受欢迎的.

例如,iOS文档更详细地讨论了背景代码:https: //developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

相反,移动操作系统提供api(如计​​时器/警报/通知apis)在特定时间后回调您的应用程序.例如,在iOS上,您可以通过UINotificationRequest请求在未来的特定时间通知/唤醒您的应用程序:https: //developer.apple.com/reference/usernotifications/unnotificationrequest 这允许他们杀死/暂停您的应用程序以实现更好的节能,而是有一个高效的共享系统服务,用于跟踪这些通知/警报/地理围栏等.

Flutter目前不提供开箱即用的这些OS服务的任何包装器,但是使用我们的平台服务模型编写自己的包装是很简单的:flutter.io/platform-services

我们正在开发一个用于发布/共享此类服务集成的系统,以便一旦有人编写此集成(比如安排将来某个应用程序的执行),每个人都可以从中受益.

另外,更常见的问题是"是否可以运行背景Dart代码"(没有在屏幕上激活FlutterView),"还没有".我们在文件中有一个错误:https: //github.com/flutter/flutter/issues/3671

驱动这种背景代码执行的用例是当您的应用收到通知时,想要使用一些Dart代码处理它而不将您的应用程序带到前面.如果您希望我们了解有关后台代码的其他用例,欢迎提出有关该错误的评论!


raj*_*ter 18

简短的回答:不,这是不可能的,虽然我已经观察到显示器进入睡眠的不同行为.以下代码将帮助您了解Android上Flutter应用程序的不同状态,使用这些Flutter和Flutter引擎版本进行测试:

  • 框架修订版b339c71523(6小时前),2017-02-04 00:51:32
  • 引擎修订版cd34b0ef39

创建一个新的Flutter应用程序,并lib/main.dart用以下代码替换内容:

import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class LifecycleWatcher extends StatefulWidget {
  @override
  _LifecycleWatcherState createState() => new _LifecycleWatcherState();
}

class _LifecycleWatcherState extends State<LifecycleWatcher>
    with WidgetsBindingObserver {
  AppLifecycleState _lastLifecyleState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void onDeactivate() {
    super.deactivate();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("LifecycleWatcherState#didChangeAppLifecycleState state=${state.toString()}");
    setState(() {
      _lastLifecyleState = state;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_lastLifecyleState == null)
      return new Text('This widget has not observed any lifecycle changes.');
    return new Text(
        'The most recent lifecycle state this widget observed was: $_lastLifecyleState.');
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter App Lifecycle'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _timerCounter = 0;
  // ignore: unused_field only created once
  Timer _timer;

  _MyHomePageState() {
    print("_MyHomePageState#constructor, creating new Timer.periodic");
    _timer = new Timer.periodic(
        new Duration(milliseconds: 3000), _incrementTimerCounter);
  }

  void _incrementTimerCounter(Timer t) {
    print("_timerCounter is $_timerCounter");
    setState(() {
      _timerCounter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(config.title),
      ),
      body: new Block(
        children: [
          new Text(
            'Timer called $_timerCounter time${ _timerCounter == 1 ? '' : 's' }.',
          ),
          new LifecycleWatcher(),
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

启动应用程序时,_timerCounter的值每3秒递增一次.计数器下方的文本字段将显示Flutter应用程序的任何AppLifecycleState更改,您将在Flutter调试日志中看到相应的输出,例如:

[raju@eagle:~/flutter/helloworld]$ flutter run
Launching lib/main.dart on SM N920S in debug mode...
Building APK in debug mode (android-arm)...         6440ms
Installing build/app.apk...                         6496ms
I/flutter (28196): _MyHomePageState#constructor, creating new Timer.periodic
Syncing files to device...
I/flutter (28196): _timerCounter is 0

  To hot reload your app on the fly, press "r" or F5. To restart the app entirely, press "R".
The Observatory debugger and profiler is available at: http://127.0.0.1:8108/
For a more detailed help message, press "h" or F1. To quit, press "q", F10, or Ctrl-C.
I/flutter (28196): _timerCounter is 1
I/flutter (28196): LifecycleWatcherState#didChangeAppLifecycleState state=AppLifecycleState.paused
I/flutter (28196): _timerCounter is 2
I/flutter (28196): _timerCounter is 3
I/flutter (28196): LifecycleWatcherState#didChangeAppLifecycleState state=AppLifecycleState.resumed
I/flutter (28196): _timerCounter is 4
I/flutter (28196): LifecycleWatcherState#didChangeAppLifecycleState state=AppLifecycleState.paused
I/flutter (28196): _timerCounter is 5
I/flutter (28196): _timerCounter is 6
I/flutter (28196): _timerCounter is 7
I/flutter (28196): LifecycleWatcherState#didChangeAppLifecycleState state=AppLifecycleState.resumed
I/flutter (28196): LifecycleWatcherState#didChangeAppLifecycleState state=AppLifecycleState.paused
I/flutter (28196): _timerCounter is 8
I/flutter (28196): _MyHomePageState#constructor, creating new Timer.periodic
I/flutter (28196): _timerCounter is 0
I/flutter (28196): _timerCounter is 1
Run Code Online (Sandbox Code Playgroud)

对于上面的日志输出,这是我做的步骤:

  1. 启动应用程序 flutter run
  2. 切换到其他应用程序(_timerCounter值1)
  3. 返回Flutter app(_timerCounter value 3)
  4. 按下电源按钮,显示屏关闭(_timerCounter value 4)
  5. 解锁手机,Flutter应用程序恢复(_timerCounter值7)
  6. 按下电话上的按钮(_timerCounter值未更改).这是FlutterActivity被破坏的时刻,也是Dart VM Isolate.
  7. Flutter app恢复(_timerCounter值再次为0)

在应用程序之间切换,按下电源或后退按钮
切换到另一个应用程序时,或按下电源按钮以关闭屏幕时,计时器继续运行.但是当Flutter应用程序具有焦点时按下后退按钮,活动会被破坏,并且随之而来的是Dart隔离.您可以在应用程序之间切换或转动屏幕时连接到Dart天文台进行测试.天文台将展示一个活跃的Flutter应用程序隔离运行.但是当按下后退按钮时,天文台显示没有运行隔离.在运行Android 6.x的Galaxy Note 5和运行Android 4.4.x的Nexus 4上确认了该行为.

展开应用生命周期和Android生命周期 对于Flutter小部件图层,仅显示已暂停和已恢复的状态.对于Android Flutter应用,Android Activity会处理销毁:

/**
 * @see android.app.Activity#onDestroy()
 */
@Override
protected void onDestroy() {
    if (flutterView != null) {
        flutterView.destroy();
    }
    super.onDestroy();
}
Run Code Online (Sandbox Code Playgroud)

由于Flutter应用程序的Dart VM在Activity内部运行,因此每次Activity被销毁时VM都将停止.

Flutter Engine代码逻辑
这不会直接回答您的问题,但会为您提供有关Flutter引擎如何处理Android状态更改的更详细背景信息.
通过Flutter引擎代码,当FlutterActivity收到Android Activity#onPause事件时,很明显动画循环暂停.当应用程序进入暂停状态时,根据源评论,会发生以下情况:

"用户当前看不到该应用程序.当应用程序处于此状态时,引擎将不会调用[onBeginFrame]回调."

根据我的测试,即使暂停UI渲染,计时器仍然可以继续工作,这是有道理的.当Activity被销毁时,使用WidgetsBindingObserver将事件发送到窗口小部件层会很好,因此开发人员可以确保存储Flutter应用程序的状态,直到恢复活动.


Jeh*_*ser 8

我遇到了同样的问题,我对这种特定情况(倒数计时器)的解决方案是使用与一些本机 android/ios 应用程序中使用的逻辑相同的逻辑,即:

  1. 当 App 暂停(发送到后台)时,我存储结束的 DateTime 对象。
  2. 当应用程序恢复(再次在前台)时,我重新计算当前设备时间(Datetime.now())和存储的结束日期时间对象之间的持续时间。 Duration remainingTime = _endingTime.difference(dateTimeNow);
  3. 使用新的持续时间更新倒数计时器值。

注意:结束日期时间值已存储在单例中,我没有使用SharedPreferences,因为在我的情况下不需要,但如果您需要它,它是一个可以接受的选项。

详情:

我创建了这个处理程序来设置和获取剩余时间:

class TimerHandler {
  DateTime _endingTime;

  TimerHandler._privateConstructor();
  TimerHandler();

  static final TimerHandler _instance = new TimerHandler();
  static TimerHandler get instance => _instance;

  int get remainingSeconds {
    final DateTime dateTimeNow = new DateTime.now();
    Duration remainingTime = _endingTime.difference(dateTimeNow);
    // Return in seconds
    return remainingTime.inSeconds;
  }

  void setEndingTime(int durationToEnd) {
    final DateTime dateTimeNow = new DateTime.now();

    // Ending time is the current time plus the remaining duration.
    this._endingTime = dateTimeNow.add(
      Duration(
        seconds: durationToEnd,
      ),
    );

  }
}
final timerHandler = TimerHandler.instance;

Run Code Online (Sandbox Code Playgroud)

然后在计时器屏幕内,我观察了应用程序的生命周期;

  • 所以一旦发送到后台(暂停)我会保存结束时间,
  • 一旦它再次进入前台(恢复),我就会用新的剩余时间启动计时器(而不是直接从新的持续时间开始,如果需要,您可以在发送到后台之前检查状态是否已暂停或启动)。

笔记:

1-在设置新的剩余持续时间之前我不检查计时器状态,因为我在我的应用程序中需要的逻辑是在用户暂停计时器的情况下推送结束时间,而不是减少 timerDuration,完全取决于用例.

2- 我的计时器生活在一个区块中(TimerBloc)。

class _TimerScreenState extends State<TimerScreen> {
  int remainingDuration;
//...

  @override
  void initState() {
    super.initState();

    SystemChannels.lifecycle.setMessageHandler((msg) {

      if (msg == AppLifecycleState.paused.toString() ) {
        // On AppLifecycleState: paused
        remainingDuration = BlocProvider.of<TimerBloc>(context).currentState.duration ?? 0;
        timerHandler.setEndingTime(remainingDuration);
        setState((){});
      }

      if (msg == AppLifecycleState.resumed.toString() ) {
        // On AppLifecycleState: resumed
        BlocProvider.of<TimerBloc>(context).dispatch(
          Start(
            duration: timerHandler.remainingSeconds,
          ),
        );
        setState((){});
      }
      return;
    });
  }

//....
}
Run Code Online (Sandbox Code Playgroud)

如果有什么不清楚的,请发表评论。


tim*_*tim 6

您可以使用flutter_workmanager插件。
它比上面提到的更好,AlarmManager因为 Android 不再推荐这样做。
该插件也始终用于iOS后台执行

该插件允许您注册一些后台工作并在发生时在 Dart 中获取回调,以便您可以执行自定义操作。

void callbackDispatcher() {
  Workmanager.executeTask((backgroundTask) {
    switch(backgroundTask) {
      case Workmanager.iOSBackgroundTask:
      case "firebaseTask":
        print("You are now in a background Isolate");
        print("Do some work with Firebase");
        Firebase.doSomethingHere();
        break;
    }
    return Future.value(true);
  });
}

void main() {
  Workmanager.initialize(callbackDispatcher);
  Workmanager.registerPeriodicTask(
    "1",
    "firebaseTask",
    frequency: Duration(days: 1),
    constraints: WorkManagerConstraintConfig(networkType: NetworkType.connected),
  );
  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

  • 周期性后台进程似乎在 iOS 上不起作用 (2认同)