Flutter Alarm Manager Schedule Task with Alaram

Last updated Dec 27, 2021


In this Flutter example tutorial we will cover how to create Alarm in flutter and schedule a task with Alarm Manager. Alarm Manager acts as a link between the application and the Android system alarm service. It can send a broadcast to your app (which the user can entirely discontinue) at a certain time, and your app can then conduct any task as a result. The system can postpone any alarm in order to improve device performance.

In this example to use alarm we are using Android Alaram Manager plugin.

 

Let's get Started

Step 1: Create Flutter application

Step 2: Add required dependencies in pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  android_alarm_manager: ^2.0.2
  flutter_local_notifications: ^9.1.5

 

Step 3: Import package

import 'package:android_alarm_manager/android_alarm_manager.dart';

 

Step 4: AndroidAlarmManager has 3 types of events to execute task

  • AndroidAlarmManager.oneShot
  • AndroidAlarmManager.oneShotAt
  • AndroidAlarmManager.periodic

 

AndroidAlarmManager.oneShot():

This Schedules a one-shot timer to run `callback` at `time. The `callback` will run whether or not the main application is running or in the foreground

 

Below code will gives the example to how to work with Alarm Manager

import 'package:android_alarm_manager/android_alarm_manager.dart';

int alarmId = 1;

// ignore: unused_element
void _examples() {
  // runs alarm timer once with time delay
  AndroidAlarmManager.oneShot(
    Duration(seconds: 5),
    alarmId,
    fireAlarm,
  );  // runs alarm timer at exact time
  AndroidAlarmManager.oneShotAt(
    // date time format (year,month,date,hour,minutes,seconds)
    DateTime(2021, 02, 18, 14, 10),
    alarmId,
    fireAlarm,
  );
  // runs callback function repeatedly
  AndroidAlarmManager.periodic(
    // must be higher than 60 seconds
    Duration(seconds: 60),
    alarmId,
    fireAlarm,
  );
}

void fireAlarm() {
  print('Alarm Fired at${DateTime.now()}');
}

 

 

If we want to run in android we should update manifest file with below permissions and receiver component inside application tag

 

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

 

<service
    android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmService"
    android:permission="android.permission.BIND_JOB_SERVICE"
    android:exported="false"/>
<receiver
    android:name="dev.fluttercommunity.plus.androidalarmmanager.AlarmBroadcastReceiver"
    android:exported="false"/>
<receiver
    android:name="dev.fluttercommunity.plus.androidalarmmanager.RebootBroadcastReceiver"
    android:enabled="false">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>

 

 

We should initialize Alarm Manager with below code


  await AndroidAlarmManager.initialize();

 

 

Complete Flutter code to Schedule Task with Alarm Manager

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isOn = false;
  int alarmId = 1;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Transform.scale(
          scale: 2,
          child: Switch(
            value: isOn,
            onChanged: (value) {
              setState(() {
                isOn = value;
              });
              if (isOn == true) {
                AndroidAlarmManager.oneShot(
                    Duration(seconds: 6), alarmId, fireAlarm);
              } else {
                AndroidAlarmManager.cancel(alarmId);
                print('Alarm Timer Canceled');
              }
            },
          ),
        ),
      ),
    );
  }
}

void fireAlarm() {
  print('Alarm Fired at ssadasd ${DateTime.now()}');
  setNotification();
}

 

This above code will execute a task after 6 seconds. And we can also set the Local Notification on particular time with Local Notification plugin

void setNotification() async {
  print('Alaram Tiggered trigger notification set');

  //Read some more stuff from sharedpreference and/or firebase. Use that information for the notification text.


  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
  var initializationSettingsAndroid =
  new AndroidInitializationSettings('mipmap/ic_launcher');
  var initializationSettingsIOS = new IOSInitializationSettings(
      onDidReceiveLocalNotification: (i, string1, string2, string3) {
        print("received notifications");
      });

  var initializationSettings = new InitializationSettings(
      android: initializationSettingsAndroid, iOS:initializationSettingsIOS);

  flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: (string) {
        print("selected notification");
      });

  var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      '12', 'eqweqw',
      importance: Importance.max, priority: Priority.high);
  var iOSPlatformChannelSpecifics = IOSNotificationDetails();
  var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics, iOS:iOSPlatformChannelSpecifics);
  await flutterLocalNotificationsPlugin.show(1, 'Zugdfda',
      'Android & Flutter Tutorialsfsd', platformChannelSpecifics,
      payload: 'item x');
}

 

main.dart file

import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_alaram_manager/home_page.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:intl/intl.dart';
import 'dart:isolate';
import 'dart:math';
import 'dart:ui';

void main() async {
  await AndroidAlarmManager.initialize();
  runApp(MyApp());

}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Alarm Manager',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}

 

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

970 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions