Skip to main content

auto_start_flutter 1.6.0 copy "auto_start_flutter: ^1.6.0" to clipboard
auto_start_flutter: ^1.6.0 copied to clipboard

Manage background execution on Android, iOS, macOS, Windows and Linux - OEM auto-start settings, battery optimization, exact alarms, boot callbacks and scheduled headless tasks.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:auto_start_flutter/auto_start_flutter.dart';

@pragma('vm:entry-point')
Future<void> myBootCallback() async {
  WidgetsFlutterBinding.ensureInitialized();
  debugPrint("Boot Callback execution triggered! The device just booted.");
  await AutoStart.completeBackgroundTask();
}

@pragma('vm:entry-point')
Future<void> myScheduledTaskCallback() async {
  WidgetsFlutterBinding.ensureInitialized();
  debugPrint("Scheduled Task execution triggered! Running headlessly.");
  await AutoStart.completeBackgroundTask();
}

@pragma('vm:entry-point')
Future<void> myExecuteInBackgroundCallback() async {
  WidgetsFlutterBinding.ensureInitialized();
  debugPrint("Execute In Background triggered! Running headlessly right now.");
  await AutoStart.completeBackgroundTask();
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _batteryOptimizationStatus = "Unknown";
  String _exactAlarmStatus = "Unknown";
  String _manufacturer = "Unknown";
  String _launchArgs = "None";

  @override
  void initState() {
    super.initState();
    initAutoStart();
    _getManufacturer();
    _checkLaunchArgs();
    _checkExactAlarm();
  }

  Future<void> _checkExactAlarm() async {
    bool canSchedule = await AutoStart.canScheduleExactAlarms();
    setState(() {
      _exactAlarmStatus = canSchedule ? "Allowed (Yes)" : "Denied (No)";
    });
  }

  Future<void> _openExactAlarm() async {
    bool success =
        await AutoStart.openExactAlarmSettings() == SettingsResult.opened;
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(success
            ? "Opening Exact Alarm Settings..."
            : "Could not open Exact Alarm settings (pre-Android 12 or unsupported).")));
  }

  Future<void> _openBatteryOptimizationSettings() async {
    bool success = await AutoStart.openBatteryOptimizationSettings() ==
        SettingsResult.opened;
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(success
            ? "Opening Battery Optimization Settings..."
            : "Could not open Battery Optimization settings.")));
  }

  Future<void> _checkLaunchArgs() async {
    final args = await AutoStart.getLaunchArguments();
    if (args.isNotEmpty) {
      setState(() {
        _launchArgs = args.toString();
      });
      debugPrint("App launched with arguments: $args");
    }
  }

  Future<void> _getManufacturer() async {
    String? manufacturer = await AutoStart.getManufacturer();
    if (manufacturer != null) {
      setState(() {
        _manufacturer = manufacturer;
      });
    }
  }

  //initializing the autoStart with the first build.
  Future<void> initAutoStart() async {
    try {
      //check auto-start availability.
      var isAvailable = await AutoStart.isAutoStartSettingsAvailable();
      debugPrint("Auto start available: $isAvailable");
      //if available then navigate to auto-start setting page.
      if (isAvailable) {
        bool success =
            await AutoStart.openAutoStartSettings() == SettingsResult.opened;
        debugPrint("Auto start permission open success: $success");
      }
    } on PlatformException catch (e) {
      debugPrint(e.toString());
    }
    if (!mounted) return;
  }

  Future<void> _checkBatteryOptimization() async {
    bool? isDisabled = await AutoStart.isBatteryOptimizationDisabled();
    setState(() {
      _batteryOptimizationStatus =
          isDisabled == true ? "Disabled (Good)" : "Enabled (Bad)";
    });
  }

  Future<void> _disableBatteryOptimization() async {
    await AutoStart.requestIgnoreBatteryOptimization();
  }

  Future<void> _openAutoStart() async {
    bool success =
        await AutoStart.openAutoStartSettings() == SettingsResult.opened;
    if (!success) {
      if (!mounted) return;
      // Now this context is below MaterialApp, so ScaffoldMessenger works.
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text("Could not open Auto-Start settings directly.")));
    }
  }

  Future<void> _openAppInfo() async {
    await AutoStart.openAppInfo();
  }

  final TextEditingController _packageNameController = TextEditingController();
  final TextEditingController _activityNameController = TextEditingController();

  @override
  void dispose() {
    _packageNameController.dispose();
    _activityNameController.dispose();
    super.dispose();
  }

  Future<void> _openCustomSetting() async {
    if (_packageNameController.text.isEmpty ||
        _activityNameController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text("Please enter both package and activity names")));
      return;
    }
    bool success = await AutoStart.openCustomSetting(
          packageName: _packageNameController.text,
          activityName: _activityNameController.text,
        ) ==
        SettingsResult.opened;
    if (!success) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("Failed to open custom setting")));
    }
  }

  Future<void> _testRegisterBootCallback() async {
    bool success = await AutoStart.registerBootCallback(myBootCallback);
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Boot Callback Registered: $success")));
  }

  Future<void> _testStartForegroundService() async {
    bool success = await AutoStart.startForegroundService(
      title: "Example Foreground Service",
      content: "This prevents the app from being killed.",
    );
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Started Foreground Service: $success")));
  }

  Future<void> _testStopForegroundService() async {
    bool success = await AutoStart.stopForegroundService();
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Stopped Foreground Service: $success")));
  }

  Future<void> _testScheduleTask() async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (timeOfDay != null) {
      final now = DateTime.now();
      var scheduledDate = DateTime(
        now.year,
        now.month,
        now.day,
        timeOfDay.hour,
        timeOfDay.minute,
      );

      // If the selected time is before now, schedule for tomorrow
      if (scheduledDate.isBefore(now)) {
        scheduledDate = scheduledDate.add(const Duration(days: 1));
      }

      final result = await AutoStart.scheduleTask(
          scheduledDate, myScheduledTaskCallback,
          taskId: "test_task_${scheduledDate.millisecondsSinceEpoch}");
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(
              "Task Scheduled for ${scheduledDate.toLocal()}: ${result.name}")));
    }
  }

  Future<void> _testExecuteInBackground() async {
    bool success =
        await AutoStart.executeInBackground(myExecuteInBackgroundCallback);
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Execute in Background: $success")));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Auto Start Flutter Example'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Manufacturer: $_manufacturer"),
              SizedBox(height: 10),
              Text("Launch Args: $_launchArgs"),
              SizedBox(height: 20),
              Text("Battery Optimization: $_batteryOptimizationStatus"),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: _checkBatteryOptimization,
                child: Text("Check Battery Optimization"),
              ),
              ElevatedButton(
                onPressed: _disableBatteryOptimization,
                child: Text("Disable Battery Optimization (Direct Dialog)"),
              ),
              ElevatedButton(
                onPressed: _openBatteryOptimizationSettings,
                child: Text("Open Battery Settings (Google Play Safe)"),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _openAutoStart,
                child: Text("Open Auto Start Settings"),
              ),
              ElevatedButton(
                onPressed: _openAppInfo,
                child: Text("Open App Info"),
              ),
              Divider(height: 40),
              Text("Test Custom Intent",
                  style: TextStyle(fontWeight: FontWeight.bold)),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  controller: _packageNameController,
                  decoration: InputDecoration(
                      labelText: "Package Name", border: OutlineInputBorder()),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  controller: _activityNameController,
                  decoration: InputDecoration(
                      labelText: "Activity Name", border: OutlineInputBorder()),
                ),
              ),
              ElevatedButton(
                onPressed: _openCustomSetting,
                child: Text("Open Custom Setting"),
              ),
              Divider(height: 40),
              Text("Phase 1 Features",
                  style: TextStyle(fontWeight: FontWeight.bold)),
              ElevatedButton(
                onPressed: _testRegisterBootCallback,
                child: Text("Register Boot Callback"),
              ),
              ElevatedButton(
                onPressed: _testStartForegroundService,
                child: Text("Start Foreground Service"),
              ),
              ElevatedButton(
                onPressed: _testStopForegroundService,
                child: Text("Stop Foreground Service"),
              ),
              Divider(height: 40),
              Text("Phase 2 Features (Exact Alarms & Tasks)",
                  style: TextStyle(fontWeight: FontWeight.bold)),
              Text("Exact Alarm: $_exactAlarmStatus"),
              SizedBox(height: 6),
              ElevatedButton(
                onPressed: _checkExactAlarm,
                child: Text("Check Exact Alarm (Android 12+)"),
              ),
              ElevatedButton(
                onPressed: _openExactAlarm,
                child: Text("Open Exact Alarm Settings"),
              ),
              ElevatedButton(
                onPressed: _testScheduleTask,
                child: Text("Schedule Task (Pick Time)"),
              ),
              Divider(height: 40),
              Text("Phase 3 Features",
                  style: TextStyle(fontWeight: FontWeight.bold)),
              ElevatedButton(
                onPressed: _testExecuteInBackground,
                child: Text("Test Headless Execution"),
              ),
              SizedBox(height: 40),
            ],
          ),
        ),
      ),
    );
  }
}
75
likes
160
points
1.08k
downloads

Documentation

API reference

Publisher

verified publishertechflow.ir

Weekly Downloads

Manage background execution on Android, iOS, macOS, Windows and Linux - OEM auto-start settings, battery optimization, exact alarms, boot callbacks and scheduled headless tasks.

Repository (GitHub)
View/report issues

License

Apache-2.0, MIT (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on auto_start_flutter

Packages that implement auto_start_flutter