You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何停止并重新调度Flutter后台服务实现定时API调用?

使用flutter_background_service实现低功耗的15分钟间隔API调用

核心思路

放弃持续运行的Timer.periodic模式,改用单次任务+系统级延迟调度的方案:每次启动服务仅执行一次API调用,完成后立即停止服务,同时调度15分钟后的下一次任务启动。这种方式避免了后台服务长期驻留,大幅降低功耗。

具体实现步骤

1. 初始化后台服务

配置服务为非前台模式(减少系统资源占用),并关闭自动启动,由调度任务触发启动。

import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:http/http.dart' as http;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await initializeBackgroundService();
  runApp(const MyApp());
}

Future<void> initializeBackgroundService() async {
  final service = FlutterBackgroundService();
  
  await service.configure(
    iosConfiguration: IosConfiguration(
      autoStart: false,
      onForeground: onServiceStart,
      onBackground: onIosBackground,
    ),
    androidConfiguration: AndroidConfiguration(
      autoStart: false,
      onStart: onServiceStart,
      isForegroundMode: false, // 禁用前台模式,降低功耗
      notificationChannelId: 'background_api_channel',
      initialNotificationTitle: '后台任务调度中',
      initialNotificationContent: '等待下一次API调用',
    ),
  );

  // 启动首次任务
  await service.startService();
}

// iOS后台回调,需返回true以允许后台执行
bool onIosBackground(ServiceInstance service) {
  WidgetsFlutterBinding.ensureInitialized();
  return true;
}

2. 编写服务核心逻辑

服务启动后执行API调用,完成后停止服务并调度下一次任务:

void onServiceStart(ServiceInstance service) async {
  // 执行API调用
  try {
    await fetchDataFromApi();
    print('API调用成功完成');
  } catch (error) {
    print('API调用失败: $error');
  }

  // 停止当前服务,释放资源
  await service.stopSelf();

  // 调度15分钟后的下一次任务
  const fifteenMinutesInMs = 15 * 60 * 1000;
  await service.scheduleTask(
    taskId: 'periodic_api_refresh',
    delay: fifteenMinutesInMs,
    periodic: false, // 设置为单次任务,避免重复调度
    androidConfiguration: AndroidConfiguration(
      onStart: onServiceStart, // 下一次触发时再次执行服务逻辑
    ),
    iosConfiguration: IosConfiguration(
      onForeground: onServiceStart,
    ),
  );
}

// 自定义API调用函数,替换为你的实际业务逻辑
Future<void> fetchDataFromApi() async {
  final response = await http.get(Uri.parse('https://your-api-endpoint.com/data'));
  if (response.statusCode != 200) {
    throw Exception('API请求失败,状态码: ${response.statusCode}');
  }
  // 处理返回数据(如存储到本地、更新UI等)
}

关键注意事项

  • Android权限配置:在android/app/src/main/AndroidManifest.xml中添加必要权限:
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- Android 12+ 必需 -->
    
  • iOS后台配置:在ios/Runner/Info.plist中添加后台模式支持:
    <key>UIBackgroundModes</key>
    <array>
      <string>fetch</string>
      <string>remote-notification</string>
    </array>
    
  • 系统调度限制:iOS的后台任务调度受系统管控,可能不会严格按照15分钟执行(系统会根据设备电量、活跃状态调整);Android端需确保应用未被用户强制关闭。

内容的提问来源于stack exchange,提问作者Vishnubly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:33:27