android - Flutter android_alarm_manager 插件不定期运行

标签 android flutter

我试图在 Flutter 中创建后台计时器,它将每 n 秒调用一次。调用 AndroidAlarmManager.periodic 应该每 2 秒运行一次 printHello 函数,但看起来它是随机调用的,间隔更大。我做错了什么?

import 'package:android_alarm_manager/android_alarm_manager.dart';


void runTimer()  async{
  await AndroidAlarmManager.periodic(const Duration(seconds: 2), 0, printHello, exact: true);
}

void printHello(){
  print("Hello");
}

main() async {
  await AndroidAlarmManager.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: Center(
          child: InkWell(onTap: runTimer,
              child: Container(child: Text('Run Timer'))),
        ),
      ),
    );
  }
}

最佳答案

您不能使用 AlarmManager 安排如此频繁的闹钟:

Note: Beginning with API 19 (Build.VERSION_CODES.KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, android.app.PendingIntent) and setExact(int, long, android.app.PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

参见:https://developer.android.com/reference/android/app/AlarmManager

关于android - Flutter android_alarm_manager 插件不定期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56012041/

相关文章:

Android加载原生库

flutter - 如何从我的 Flutter 代码中打开 Web 浏览器 (URL)?

android-studio - 如何在 Android Studio 中为 Flutter 项目启用自动热重载?

ios - 应该在插件中的什么位置添加 iOS 依赖项?

android - 为 x86 和 x86_64 构建 Flutter 应用程序

android - Flutter Android Embedding V1 和 V2 有什么区别

java - 当我尝试从数据库中删除数据并刷新 ListView 时,应用程序崩溃了

android - 适用于 Android 5.0 的 Google API

java - 使用 onTouchListener 旋转图像而不缩放图像

php - 如何使用 HttpUrlConnection 通过 POST 传递参数