Flutter android_alarm_manager插件不会定期运行 [英] Flutter android_alarm_manager plugin doesnt run periodically

查看:89
本文介绍了Flutter android_alarm_manager插件不会定期运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to create background timer in Flutter, that will be called every n seconds. Calling AndroidAlarmManager.periodic should run printHello function every 2 seconds, but it looks like it is called randomly with much more larger interval. What Im doing wrong?

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频繁安排警报:

You can't schedule an alarm that frequently with AlarmManager:

注意:从API 19(Build.VERSION_CODES.KITKAT)开始,警报传递是不精确的:操作系统将转移警报,以最大程度地减少唤醒和电池消耗.有一些新的API支持需要严格交付保证的应用程序.请参见setWindow(int,long,long,android.app.PendingIntent)和setExact(int,long,android.app.PendingIntent). targetSdkVersion早于API 19的应用程序将继续看到以前的行为,在该行为中,所有警报均在请求时准确地传递.

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

这篇关于Flutter android_alarm_manager插件不会定期运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆