我试图在 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/