搜索插件、代码仓与 APP 分类

插件详情v1.6.0

auto_start_flutter

一个用于管理后台执行权限的 Flutter 插件。支持 Android 自启动设置(小米等)和 iOS 后台应用刷新。

AndroidiOSmacOSWindowsLinux
近 30 天下载
2110
喜欢数
76
Pub 分数
160

安装插件

flutter pub add auto_start_flutter

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

auto_start_flutter 是一个 Flutter 插件,可帮助在 Android 和 iOS 平台上管理后台执行权限。它使应用程序能够访问 Android 设备(包括小米、三星等)的自动启动设置,并支持 iOS 的后台应用刷新。该包简化了处理平台特定权限请求和配置的过程,确保一致的后台行为。对于需要后台任务的应用程序(如推送通知、位置跟踪或定期数据同步)非常理想。该插件可无缝集成到 Flutter 项目中,并支持多个平台,包括 macOS、Windows 和 Linux。

适合场景

  • 在 iOS 上启用后台应用刷新
  • 在 Android 上授予自动启动权限
  • 支持后台任务执行
  • 管理设备特定的省电设置
  • 确保可靠的推送通知传递

主要特点

  • 跨平台后台权限管理
  • 支持 Android 自启动设置(小米等)
  • iOS 后台应用刷新集成
  • 平台无关的 API 设计
  • 多平台支持(Android、iOS、macOS、Windows、Linux)

适合对象

  • 需要持久后台执行的应用程序
  • 针对严格电源管理的 Android OEM 开发者
  • 需要可靠推送通知的项目
  • 跨平台移动应用
  • 使用后台位置或数据同步的应用

使用建议

  • 需要在 Android 和 iOS 上获取用户权限
  • 可能需要为特定OEM进行额外配置
  • 操作系统策略限制了后台执行
  • 并非所有设备都支持相同的后台行为
  • 用户可能需要在系统设置中手动启用权限

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

auto_start_flutter

A Flutter plugin to help manage background execution permissions on Android, iOS, macOS, Windows, and Linux devices. It supports requesting "Auto-Start" permissions on specific Android OEM devices, checking "Background App Refresh" status on iOS, and managing "Startup Apps / Login Items" settings on Windows and macOS to ensure your app can run reliably in the background.

Features

  • Auto-Start Permission:
    • Android: Open manufacturer-specific "Auto-Start" or "App Launch" settings.
    • iOS: Check Background App Refresh status.
    • Windows/macOS: Open the "Startup Apps" or "Login Items" system settings.
  • Battery Optimization: Check if the app is exempt from battery optimizations and open settings to request exemption (Android) or power settings (Windows/macOS).
  • Device Support:
    • Android: Xiaomi, Redmi, Poco, Oppo, Vivo, Huawei, Honor, Samsung, ASUS, OnePlus, Nokia, LeTV, Meizu, HTC, Infinix, and more.
    • iOS: All devices.
    • Windows: Windows 10/11.
    • macOS: macOS 10.14+ (limitations apply).
    • Linux: Supported (stubbed methods due to varying Desktop Environments).
  • Robustness: The plugin attempts multiple known intents for each manufacturer to ensure the settings page opens correctly.

pub package

Getting Started

Add the package to your pubspec.yaml:

  auto_start_flutter: ^1.5.0

Import the package:

import 'package:auto_start_flutter/auto_start_flutter.dart';

Platform Support

Feature Android iOS Windows macOS Linux
isAutoStartAvailable Checks manufacturer whitelist Checks UIBackgroundRefreshStatus Returns true Returns true Returns true
getAutoStartPermission Opens Auto Start / App Info Opens App Settings Opens Startup Apps Opens Login Items Returns true (No-op)
openAppInfo Opens App Info Opens App Settings Opens Apps & Features Opens General Settings Returns true (No-op)
getDeviceManufacturer Returns Build.MANUFACTURER Returns "Apple" Returns "Microsoft" Returns "Apple" Returns "Linux"
isBatteryOptimizationDisabled Checks doze mode status Returns true (Always valid) Returns true Returns true Returns true
disableBatteryOptimization Direct dialog prompt (REQUEST_IGNORE...) Opens App Settings Opens Power & Sleep Opens Energy Saver Returns true (No-op)
openBatteryOptimizationSettings Opens battery optimization list (Google Play safe) Opens App Settings Opens Power & Sleep Opens Energy Saver Returns true (No-op)
canScheduleExactAlarms Checks AlarmManager.canScheduleExactAlarms() (Android 12+) Returns true Returns true Returns true Returns true
openExactAlarmSettings Opens "Alarms & reminders" settings (Android 12+) Returns false (No-op) Returns false (No-op) Returns false (No-op) Returns false (No-op)
openCustomSetting Opens specific activity Not Supported Not Supported Not Supported Not Supported
registerBootCallback Uses BOOT_COMPLETED trigger Not Supported Writes to Startup Registry Registers via SMAppService Writes -autostart to ~/.config/autostart/
startForegroundService Starts Foreground Service Not Supported Returns false (No-op) Returns false (No-op) Returns false (No-op)
executeInBackground Headless Engine Headless Engine Hidden Process Headless Engine Hidden Process

Usage

AutoStart Permission / Background Refresh

On Android, this checks if the device is from a manufacturer known to have aggressive auto-start restrictions and redirects the user to the appropriate settings page. On iOS, this checks if Background App Refresh is enabled. If not, it redirects the user to the App Settings page where they can enable it. On Windows and macOS, this opens the Startup Apps or Login Items system settings, where users can toggle your app's startup status.

import 'package:auto_start_flutter/auto_start_flutter.dart';
// ...

// 1. Check if auto-start permission is available / relevant
// Android: Returns true for Xiaomi, Oppo, Vivo, etc.
// iOS: Returns true if Background App Refresh is available (not restricted).
var isAvailable = await isAutoStartAvailable;

if (isAvailable == true) {
    // 2. Request permission / Open Settings
    // Android: Opens Auto Start settings or App Info.
    // iOS: Opens App Settings.
    // Windows/macOS: Opens Startup Apps / Login Items settings.
    await getAutoStartPermission();
}
Other Features
  1. App Info: Open the system settings page for the app.

    // Android: Opens App Info
    // iOS: Opens App Settings
    await openAppInfo();
    
  2. Device Manufacturer: Get the device manufacturer.

    String? manufacturer = await getDeviceManufacturer(); 
    // e.g. "Xiaomi", "Apple", "Samsung"
    
  3. Custom Settings (Android Only): If you know the specific package and activity name for a setting page on a specific device, you can attempt to open it directly.

    // Example: Try opening a specific hidden setting
    await openCustomSetting(
      packageName: 'com.android.settings',
      activityName: 'com.android.settings.Settings\$PowerUsageSummaryActivity',
    );
    
Background Execution & Boot

The plugin provides advanced lifecycle hooks to natively launch your app in the background across platforms.

  1. Boot Completed Trigger (registerBootCallback): Run a headless Dart callback or launch your app the moment the device turns on.

    • Android: Uses the BOOT_COMPLETED intent and spawns a secure background FlutterEngine.
    • Windows: Natively writes the executable path with an --autostart flag directly into the HKCU\Software\Microsoft\Windows\CurrentVersion\Run registry.
    • macOS: Uses the modern Apple SMAppService.mainApp.register() API to register the application into Login Items seamlessly (macOS 13+).
    • Linux: Generates a standardized X-GNOME .desktop file natively inside ~/.config/autostart/.
    import 'dart:ui';
    import 'package:flutter/material.dart';
    
    // 1. Must be a top-level or static function
    @pragma('vm:entry-point')
    void myBootCallback() {
      WidgetsFlutterBinding.ensureInitialized();
      print("Device booted! Running in the background...");
    }
    
    // 2. Register it somewhere in your app (e.g. main.dart)
    await registerBootCallback(myBootCallback);
    

    Note: On Android, you must manually add the RECEIVE_BOOT_COMPLETED permission to your AndroidManifest.xml (see Mandatory Setup below).

  2. Foreground Service Keep-Alive (Android): Start a foreground service to prevent Android from killing your app when it goes to the background. This will pin a persistent notification to the user's status bar.

    // Start the service
    await startForegroundService(
      title: "Syncing Data",
      content: "Do not close the app.",
    );
    
    // Stop the service when done
    await stopForegroundService();
    

    Note: On Android, you must manually add the FOREGROUND_SERVICE permission to your AndroidManifest.xml (see Mandatory Setup below).

  3. Exact Scheduling & Alarms (scheduleTask): Schedule a task to run precisely at a future timestamp.

    • Android: Uses AlarmManager for highly accurate background wakes, triggering a headless Dart callback even in Doze mode.
    • iOS & macOS: Apple strictly prohibits generic headless background wakes at exact times. Therefore, this API relies on UNUserNotificationCenter. It will schedule a Local Notification for the exact timestamp. When the user taps the notification, the app opens, and getLaunchArguments will contain the taskId and callbackHandle. This will prompt the user for Notification Permissions the first time it is called.
    • Windows: Natively interfaces with the Windows Task Scheduler COM API.
    • Linux: Automatically manages systemd user timers.
    final at = DateTime.now().add(Duration(minutes: 5));
    bool success = await scheduleTask(at, myScheduledTaskCallback, taskId: "my_task_1");
    
    // On app startup, check if we were launched by a scheduled task
    final args = await getLaunchArguments();
    if (args['scheduledTaskId'] == 'my_task_1') {
      print("Woke up from scheduled task!");
    }
    

    Exact Alarm Permissions (Android 12+ / API 31+): Starting in Android 12, apps scheduling exact alarms must verify permission:

    // Check if exact alarms can be scheduled
    bool canSchedule = await canScheduleExactAlarms();
    
    if (!canSchedule) {
      // Guide user to the system "Alarms & reminders" settings page
      await openExactAlarmSettings();
    }
    
  4. Headless Execution (executeInBackground) (Phase 3): Execute a Dart callback immediately in the background without bringing the app to the foreground or attaching a UI.

    • Android/Apple: Instantiates a dedicated headless FlutterEngine / Isolate.
    • Desktop (Windows/Linux): Spawns a hidden background process via the native executable.
    // 1. Must be a top-level or static function
    @pragma('vm:entry-point')
    void myHeadlessTask() {
      WidgetsFlutterBinding.ensureInitialized();
      print("Running in the background instantly!");
    }
    
    // 2. Trigger execution
    await executeInBackground(myHeadlessTask);
    
Battery Optimization (Android, Windows, macOS, Linux)

Android's Doze mode and App Standby can restrict background processing. On Windows and macOS, energy/power settings can similarly affect background performance.

  1. Check Status: Check if your app is already ignoring battery optimizations.

    bool isExempt = await isBatteryOptimizationDisabled ?? false;
    print("Battery Optimization Disabled: $isExempt");
    
  2. Open Battery Optimization Settings (Recommended & Google Play Safe): Navigates the user to the standard system battery optimization list (ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS on Android). This does not require declaring high-risk permissions or justifying policies in Google Play Console.

    if (!isExempt) {
      await openBatteryOptimizationSettings();
    }
    
  3. Direct Dialog Exemption (Requires Policy Declaration): On Android 6.0+, prompts the user directly via a system dialog using ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS.

    [!WARNING] Google Play strictly limits apps requesting direct battery exemption dialogs. Only use disableBatteryOptimization() if your app qualifies under Google Play exemption policies. Otherwise, use openBatteryOptimizationSettings().

    if (!isExempt) {
      await disableBatteryOptimization();
    }
    

Platform Support

Platform Supported Notes
Android ✅ Supports custom OEM intents and standard battery optimization settings.
iOS ✅ Checks UIBackgroundRefreshStatus and opens App Settings.
Windows ✅ Opens Startup Apps settings.
macOS ✅ Opens Login Items settings.
Linux ✅ Basic support. Most methods return logical defaults as DE APIs vary wildly.

Note: Standard Android APIs do not allow checking if "Auto Start" is actually enabled. isAutoStartAvailable only returns true if the device manufacturer is on the supported list (e.g. Xiaomi, Oppo). On Windows and macOS, isAutoStartAvailable returns true to indicate that the "Startup Apps" / "Login Items" setting is accessible. Only iOS allows verifying the actual background refresh status programmatically.

Mandatory Setup (Android)

To keep the plugin lightweight and privacy-focused, permissions are no longer included by default. You must add the permissions required for the features you intend to use to your android/app/src/main/AndroidManifest.xml.

1. Boot Completed Trigger

Required for registerBootCallback.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2. Foreground Service

Required for startForegroundService.

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- For Android 14+ -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
3. Exact Scheduling & Alarms (Phase 2)

Required for scheduleTask.

<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- For Android 13+ -->
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
4. Battery Optimization Exemption

Required for disableBatteryOptimization (direct dialog prompt):

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

Note: If you use openBatteryOptimizationSettings(), no special permission is required in your AndroidManifest.xml!

5. Headless Execution (Phase 3)

No special permissions are strictly required for executeInBackground to spin up the background isolate. However, if your headless task requires internet access or long-running CPU locks, ensure standard Flutter network permissions or battery optimization exemptions are handled.

Contributing

If you find any issues or would like to add support for more devices, please file an issue or pull request on GitHub.

所属分类

依赖

依赖清单 1 项

  • plugin_platform_interface^2.1.8

源码仓库

使用此插件的项目