android_alarm_manager 0.4.5+11

  • Readme
  • Changelog
  • Example
  • Installing
  • 97

android_alarm_manager #

pub package

A Flutter plugin for accessing the Android AlarmManager service, and running Dart code in the background when alarms fire.

Please set your constraint to android_alarm_manager: '>=0.4.y+x <2.0.0'

Backward compatible 1.0.0 version is coming #

The plugin has reached a stable API, we guarantee that version 1.0.0 will be backward compatible with 0.4.y+z. Please use android_alarm_manager: '>=0.4.y+x <2.0.0' as your dependency constraint to allow a smoother ecosystem migration. For more details see:

Getting Started #

After importing this plugin to your project as usual, add the following to your AndroidManifest.xml within the <manifest></manifest> tags:

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

Next, within the <application></application> tags, add:

        <action android:name="android.intent.action.BOOT_COMPLETED"></action>

Then in Dart code add:

import 'package:android_alarm_manager/android_alarm_manager.dart';

void printHello() {
  final 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();
  await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello);

printHello will then run (roughly) every minute, even if the main app ends. However, printHello will not run in the same isolate as the main application. Unlike threads, isolates do not share memory and communication between isolates must be done via message passing (see more documentation on isolates here).

Using other plugins in alarm callbacks #

If alarm callbacks will need access to other Flutter plugins, including the alarm manager plugin itself, it may be necessary to inform the background service how to initialize plugins depending on which Flutter Android embedding the application is using.

Flutter Android Embedding V1 #

For the Flutter Android Embedding V1, the background service must be provided a callback to register plugins with the background isolate. This is done by giving the AlarmService a callback to call the application's onCreate method. See the example's Application overrides.

In particular, its Application class is as follows:

public class Application extends FlutterApplication implements PluginRegistrantCallback {
  public void onCreate() {

  public void registerWith(PluginRegistry registry) {

Which must be reflected in the application's AndroidManifest.xml. E.g.:


Note: Not calling AlarmService.setPluginRegistrant will result in an exception being thrown when an alarm eventually fires.

Flutter Android Embedding V2 (Flutter Version >= 1.12) #

For the Flutter Android Embedding V2, plugins are registered with the background isolate via reflection so AlarmService.setPluginRegistrant does not need to be called.

NOTE: this plugin is not completely compatible with the V2 embedding on Flutter versions < 1.12 as the background isolate will not automatically register plugins. This can be resolved by running flutter upgrade to upgrade to the latest Flutter version.

For help getting started with Flutter, view our online documentation.

For help on editing plugin code, view the documentation.

0.4.5+11 #

  • Update lower bound of dart dependency to 2.1.0.

0.4.5+10 #

0.4.5+9 #

  • Fix CocoaPods podspec lint warnings.

0.4.5+8 #

  • Remove MainActivity references in android example app and tests.

0.4.5+7 #

  • Update minimum Flutter version to 1.12.13+hotfix.5
  • Clean up various Android workarounds no longer needed after framework v1.12.
  • Complete v2 embedding support.

0.4.5+6 #

  • Replace deprecated getFlutterEngine call on Android.

0.4.5+5 #

  • Added an Espresso test.

0.4.5+4 #

  • Make the pedantic dev_dependency explicit.

0.4.5+3 #

  • Fixed issue where callback lookup would fail while running in the background.

0.4.5+2 #

  • Remove the deprecated author: field from pubspec.yaml
  • Migrate the plugin to the pubspec platforms manifest.
  • Require Flutter SDK 1.10.0 or greater.

0.4.5+1 #

  • Loosen Flutter version restriction to 1.9.1. NOTE: plugin registration for the background isolate will not work correctly for applications using the V2 Flutter Android embedding for Flutter versions lower than 1.12.

0.4.5 #

  • Add support for Flutter Android embedding V2

0.4.4+3 #

  • Add unit tests and DartDocs.

0.4.4+2 #

  • Remove AndroidX warning.

0.4.4+1 #

  • Update and migrate iOS example project.
  • Define clang module for iOS.

0.4.4 #

  • Add id to callback if it is of type Function(int)

0.4.3 #

  • Added oneShotAt method to run callback at a given DateTime time.

0.4.2 #

  • Added support for setting alarms which work when the phone is in doze mode.

0.4.1+8 #

  • Remove dependency on google-services in the Android example.

0.4.1+7 #

  • Fix possible crash on Android devices with APIs below 19.

0.4.1+6 #

  • Bump the minimum Flutter version to 1.2.0.
  • Add template type parameter to invokeMethod calls.

0.4.1+5 #

  • Update AlarmService to throw a PluginRegistrantException if AlarmService.setPluginRegistrant has not been called to set a PluginRegistrantCallback. This improves the error message seen when the AlarmService.setPluginRegistrant call is omitted.

0.4.1+4 #

  • Updated example to remove dependency on Firebase.

0.4.1+3 #

  • Update to include instructions for setting the WAKE_LOCK permission.
  • Updated example application to use the WAKE_LOCK permission.

0.4.1+2 #

  • Include a missing API dependency.

0.4.1+1 #

  • Log a more detailed warning at build time about the previous AndroidX migration.

0.4.1 #

  • Added support for setting alarms which persist across reboots.
    • Both AndroidAlarmManager.oneShot and AndroidAlarmManager.periodic have an optional rescheduleOnReboot parameter which specifies whether the new alarm should be rescheduled to run after a reboot (default: false). If set to false, the alarm will not survive a device reboot.

    • Requires AndroidManifest.xml to be updated to include the following entries:

      <!--Within the application tag body-->
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
      <!--Within the manifest tag body-->
              <action android:name="android.intent.action.BOOT_COMPLETED"></action>

0.4.0 #

  • Breaking change. Migrated the underlying AlarmService to utilize a BroadcastReceiver with a JobIntentService instead of a Service to handle processing of alarms. This requires AndroidManifest.xml to be updated to include the following entries:

  • Fixed issue where background service was not starting due to background execution restrictions on Android 8+ (see issue #26846).

  • Fixed issue where alarm events were ignored when the background isolate was still initializing. Alarm events are now queued if the background isolate has not completed initializing and are processed once initialization is complete.

0.3.0 #

  • Breaking change. Migrate from the deprecated original Android Support Library to AndroidX. This shouldn't result in any functional changes, but it requires any Android apps using this plugin to also migrate if they're using the original support library.

0.2.3 #

  • Move firebase_auth from a dependency to a dev_dependency.

0.2.2 #

  • Update dependencies for example to point to published versions of firebase_auth.

0.2.1 #

  • Update dependencies for example to point to published versions of firebase_auth and google_sign_in.
  • Add missing dependency on firebase_auth.

0.2.0 #

  • Breaking change. A new isolate is always spawned for the background service instead of trying to share an existing isolate owned by the application.
  • Breaking change. Removed AlarmService.getSharedFlutterView.

0.1.1 #

  • Updated Gradle tooling to match Android Studio 3.1.2.

0.1.0 #

  • Breaking change. Set SDK constraints to match the Flutter beta release.

0.0.5 #

  • Simplified and upgraded Android project template to Android SDK 27.
  • Moved Android package to io.flutter.plugins.

0.0.4 #

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here.

0.0.3 #

  • Adds use of a Firebase plugin to the example. The example also now demonstrates overriding the Application's onCreate method so that the AlarmService can initialize plugin connections.

0.0.2 #

  • Add FLT prefix to iOS types.

0.0.1 #

  • Initial release.


// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:isolate';
import 'dart:math';
import 'dart:ui';

import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';

/// The [SharedPreferences] key to access the alarm fire count.
const String countKey = 'count';

/// The name associated with the UI isolate's [SendPort].
const String isolateName = 'isolate';

/// A port used to communicate from a background isolate to the UI isolate.
final ReceivePort port = ReceivePort();

/// Global [SharedPreferences] object.
SharedPreferences prefs;

Future<void> main() async {
  // TODO(bkonyi): uncomment

  // Register the UI isolate's SendPort to allow for communication from the
  // background isolate.
  prefs = await SharedPreferences.getInstance();
  if (!prefs.containsKey(countKey)) {
    await prefs.setInt(countKey, 0);

/// Example app for Espresso plugin.
class AlarmManagerExampleApp extends StatelessWidget {
  // This widget is the root of your application.
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: _AlarmHomePage(title: 'Flutter Demo Home Page'),

class _AlarmHomePage extends StatefulWidget {
  _AlarmHomePage({Key key, this.title}) : super(key: key);
  final String title;

  _AlarmHomePageState createState() => _AlarmHomePageState();

class _AlarmHomePageState extends State<_AlarmHomePage> {
  int _counter = 0;

  void initState() {

    // Register for events from the background isolate. These messages will
    // always coincide with an alarm firing.
    port.listen((_) async => await _incrementCounter());

  Future<void> _incrementCounter() async {
    print('Increment counter!');

    // Ensure we've loaded the updated count from the background isolate.
    await prefs.reload();

    setState(() {

  // The background
  static SendPort uiSendPort;

  // The callback for our alarm
  static Future<void> callback() async {
    print('Alarm fired!');

    // Get the previous cached count and increment it.
    final prefs = await SharedPreferences.getInstance();
    int currentCount = prefs.getInt(countKey);
    await prefs.setInt(countKey, currentCount + 1);

    // This will be null if we're running in the background.
    uiSendPort ??= IsolateNameServer.lookupPortByName(isolateName);

  Widget build(BuildContext context) {
    // TODO(jackson): This has been deprecated and should be replaced
    // with `headline4` when it's available on all the versions of
    // Flutter that we test.
    // ignore: deprecated_member_use
    final textStyle = Theme.of(context).textTheme.display1;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      body: Center(
        child: Column(
          children: <Widget>[
              'Alarm fired $_counter times',
              style: textStyle,
              children: <Widget>[
                  'Total alarms fired: ',
                  style: textStyle,
                  key: ValueKey('BackgroundCountText'),
                  style: textStyle,
              child: Text(
                'Schedule OneShot Alarm',
              key: ValueKey('RegisterOneShotAlarm'),
              onPressed: () async {
                await AndroidAlarmManager.oneShot(
                  const Duration(seconds: 5),
                  // Ensure we have a unique alarm ID.
                  Random().nextInt(pow(2, 31)),
                  exact: true,
                  wakeup: true,

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  android_alarm_manager: ^0.4.5+11

2. Install it

You can install packages from the command line:

with Flutter:

$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:android_alarm_manager/android_alarm_manager.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

We analyzed this package on May 23, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
pedantic ^1.8.0