FLUTTER-Android Servise | IOS BG Mode and Local Notification

Ozgenimrag
3 min readSep 21, 2022

--

Flutter-Android Servise | IOS Background Mode and Local Notification

Local notification with Android Service

— — — pubspec.yaml — — —

flutter_local_notifications: ^11.0.0

rxdart: ^0.27.5

flutter_background_service: ^2.3.8

shared_preferences: ^2.0.15

device_info_plus: ^4.1.2

— — — notification_api.dart — — —

// ignore_for_file: prefer_const_constructors

import ‘dart:io’;

import ‘package:flutter/material.dart’;

import ‘package:flutter_local_notifications/flutter_local_notifications.dart’;

import ‘package:rxdart/rxdart.dart’;

class NotificationApi {

static final _notifications = FlutterLocalNotificationsPlugin();

static final onNotifications = BehaviorSubject<String>();

static Future _notificationDetails() async {

return NotificationDetails(

android: AndroidNotificationDetails(

‘channel id’,

‘channel name’,

importance: Importance.max,

));

}

static Future init({bool initScheduled = false}) async {

final android = AndroidInitializationSettings(‘@mipmap/ic_launcher’);

final settings = InitializationSettings(android: android);

await _notifications.initialize(settings,

onDidReceiveNotificationResponse: (payload) async {

// onNotifications.add(payload);

});

}

static Future showNotification({

int id = 0,

String? title,

String? body,

String? payload,

}) async =>

_notifications.show(

id,

title,

body,

await _notificationDetails(),

payload: payload,

);

}

— — — main.dart — — —

import ‘dart:async’;

import ‘dart:ui’;

import ‘package:bildirimapp1/notification_api.dart’;

import ‘package:flutter/material.dart’;

import ‘package:flutter_background_service/flutter_background_service.dart’;

import ‘package:device_info_plus/device_info_plus.dart’;

import ‘package:flutter_background_service_android/flutter_background_service_android.dart’;

import ‘package:flutter_local_notifications/flutter_local_notifications.dart’;

import ‘package:shared_preferences/shared_preferences.dart’;

Future<void> main() async {

WidgetsFlutterBinding.ensureInitialized();

await initializeService();

// FlutterBackgroundService.initialize(onStart);

runApp(const MyApp());

}

const notificationChannelId = ‘my_foreground’;

// this will be used for notification id, So you can update your custom notification with this id.

const notificationId = 888;

Future<void> initializeService() async {

final service = FlutterBackgroundService();

const AndroidNotificationChannel channel = AndroidNotificationChannel(

notificationChannelId, // id

‘MY FOREGROUND SERVICE’, // title

description:

‘This channel is used for important notifications.’, // description

importance: Importance.low, // importance must be at low or higher level

);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =

FlutterLocalNotificationsPlugin();

await flutterLocalNotificationsPlugin

.resolvePlatformSpecificImplementation<

AndroidFlutterLocalNotificationsPlugin>()

?.createNotificationChannel(channel);

await service.configure(

androidConfiguration: AndroidConfiguration(

// this will be executed when app is in foreground or background in separated isolate

onStart: onStart,

// auto start service

autoStart: true,

isForegroundMode: true,

notificationChannelId:

notificationChannelId, // this must match with notification channel you created above.

initialNotificationTitle: ‘AWESOME SERVICE’,

initialNotificationContent: ‘Initializing’,

foregroundServiceNotificationId: notificationId,

),

iosConfiguration: IosConfiguration(

// auto start service

autoStart: true,

// this will be executed when app is in foreground in separated isolate

onForeground: onStart,

// you have to enable background fetch capability on xcode project

onBackground: onIosBackground,

),

);

service.startService();

}

bool onIosBackground(ServiceInstance service) {

WidgetsFlutterBinding.ensureInitialized();

print(‘FLUTTER BACKGROUND FETCH’);

return true;

}

String changer = “game_changer”;

Future<void> onStart(ServiceInstance service) async {

// Only available for flutter 3.0.0 and later

DartPluginRegistrant.ensureInitialized();

SharedPreferences preferences = await SharedPreferences.getInstance();

await preferences.setString(“hello”, “world”);

/// OPTIONAL when use custom notification

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =

FlutterLocalNotificationsPlugin();

if (service is AndroidServiceInstance) {

service.on(‘setAsForeground’).listen((event) {

service.setAsForegroundService();

});

service.on(‘setAsBackground’).listen((event) {

service.setAsBackgroundService();

});

}

service.on(‘stopService’).listen((event) {

service.stopSelf();

});

Timer(const Duration(seconds: 15), () async {

if (service is AndroidServiceInstance) {

if (await service.isForegroundService()) {

/// OPTIONAL for use custom notification

/// the notification id must be equals with AndroidConfiguration when you call configure() method.

flutterLocalNotificationsPlugin.show(

888,

‘COOL SERVICE’,

‘Awesome ${DateTime.now()}’,

const NotificationDetails(

android: AndroidNotificationDetails(

‘my_foreground’,

‘MY FOREGROUND SERVICE’,

icon: ‘ic_bg_service_small’,

ongoing: true,

),

),

);

}

}

NotificationApi.showNotification(

title: “ÖZGEN İMRAĞ”,

body: “Background service and local notification”,

payload: “send message content”,

);

});

}

class MyApp extends StatelessWidget {

const MyApp({Key? key}) : super(key: key);

@override

Widget build(BuildContext context) {

return MaterialApp(

home: HomePage(),

);

}

}

class HomePage extends StatefulWidget {

const HomePage({Key? key}) : super(key: key);

@override

State<HomePage> createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

String text = “Stop Service”;

@override

void initState() {

// TODO: implement initState

super.initState();

NotificationApi.init();

listenNotifications();

}

void listenNotifications() =>

NotificationApi.onNotifications.stream.listen(onClickedNotification);

void onClickedNotification(String? payload) => Navigator.of(context)

.push(MaterialPageRoute(builder: (context) => MyApp()));

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text(“Bildirim1”)),

body: Stack(

children: [

Padding(

padding: EdgeInsets.all(10),

child: Column(

children: [

TextButton(

onPressed: () {

NotificationApi.showNotification(

title: “ÖZGEN İMRAĞ”,

body: “Background service and local notification”,

payload: “send message content??”,

);

},

child: Text(“bildirim1”),

),

Column(

children: [

StreamBuilder<Map<String, dynamic>?>(

stream: FlutterBackgroundService().on(‘update’),

builder: (context, snapshot) {

if (!snapshot.hasData) {

return const Center(

child: CircularProgressIndicator(),

);

}

final data = snapshot.data!;

String? device = data[“device”];

DateTime? date =

DateTime.tryParse(data[“current_date”]);

return Column(

children: [

Text(device ?? ‘Unknown’),

Text(date.toString()),

],

);

},

),

ElevatedButton(

child: const Text(“Foreground Mode”),

onPressed: () {

FlutterBackgroundService().invoke(“setAsForeground”);

},

),

ElevatedButton(

child: const Text(“Background Mode”),

onPressed: () {

FlutterBackgroundService().invoke(“setAsBackground”);

},

),

ElevatedButton(

child: Text(text),

onPressed: () async {

final service = FlutterBackgroundService();

var isRunning = await service.isRunning();

if (isRunning) {

service.invoke(“stopService”);

} else {

service.startService();

}

if (!isRunning) {

text = ‘Stop Service’;

} else {

text = ‘Start Service’;

}

setState(() {});

},

),

],

),

],

),

)

],

),

);

}

}

--

--