解决方案 1: android_alarm_manager_plus 是安排后台任务的最佳解决方案。但唯一的缺点是只支持Android。
注意:如果您使用的是 android_alarm_manager 版本,请迁移到 Plus 版本:D
让我们开始吧:
像往常一样将此插件导入您的项目后,将以下内容添加到您的 AndroidManifest.xml 中的标签中:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
接下来,在标签内添加:
<service
android:name="io.flutter.plugins.androidalarmmanager.AlarmService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false"/>
<receiver
android:name="io.flutter.plugins.androidalarmmanager.AlarmBroadcastReceiver"
android:exported="false"/>
<receiver
android:name="io.flutter.plugins.androidalarmmanager.RebootBroadcastReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
然后在 Dart 代码中添加:
import 'package:android_alarm_manager/android_alarm_manager.dart';
void printHello() {
final DateTime now = DateTime.now();
final int isolateId = Isolate.current.hashCode;
print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
}
main() async {
final int helloAlarmID = 0;
await AndroidAlarmManager.initialize();
runApp(...);
await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello);
}
如果您想在每天的特定时间安排任何任务,您需要执行以下操作:
if (Platform.isAndroid) {
await AndroidAlarmManager.periodic(
const Duration(hours: 24), //Do the same every 24 hours
helloAlarmID, //Different ID for each alarm
printHello,
wakeup: true, //the device will be woken up when the alarm fires
startAt: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 5, 0), //Start whit the specific time 5:00 am
rescheduleOnReboot: true, //Work after reboot
);
}
如果警报回调需要访问其他 Flutter 插件,包括警报管理器插件本身,则可能需要通知后台服务如何初始化插件,具体取决于应用程序正在使用哪个 Flutter Android 嵌入。
这是通过给 AlarmService 一个回调来调用应用程序的 onCreate 方法来完成的。
具体来说,它的Application类如下:
public class Application extends FlutterApplication implements PluginRegistrantCallback {
@Override
public void onCreate() {
super.onCreate();
AlarmService.setPluginRegistrant(this);
}
@Override
public void registerWith(PluginRegistry registry) {
//add AndroidAlarmManagerPlugin plugin register if you work with arlarm
AndroidAlarmManagerPlugin.registerWith(registry.registrarFor("io.flutter.plugins.androidalarmmanager.AndroidAlarmManagerPlugin"));
}
}
这必须反映在应用程序的 AndroidManifest.xml 中。例如:
<application
android:name=".Application"
...
解决方案 2:
Cron 是安排后台任务的另一个最佳解决方案。 Cron 以固定的时间、日期或间隔定期运行任务。但是,corn 的唯一缺点是一旦应用程序被杀,cron 无法按预期在后台运行。
一个简单的用法示例:
import 'package:cron/cron.dart';
main() {
var cron = new Cron();
cron.schedule(new Schedule.parse('*/3 * * * *'), () async {
print('every three minutes');
});
cron.schedule(new Schedule.parse('8-11 * * * *'), () async {
print('between every 8 and 11 minutes');
});
}
一般如何设置 cronjob:information
测试 cronjob:crontab