I want to push a notification in both foreground and background in a flutter app when a bool flag is set to true. I gone through the example given in flutter_background_service package but I can't unserstand where to write the code to check the flag and call the method to push a notification.
What I did understand is that when the app switches to background, the onStart method is called. I have a unique username for each user, which I retrieve in the main function using shared preferences. So after fetching the username, the service should be running (in case of both foreground and background).
The following is the code I tried, but didn't get the expected result
Future<void> initializeService() async {
final service = FlutterBackgroundService();
final initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
final initializationSettings = InitializationSettings(
android:initializationSettingsAndroid);
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
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,
),
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();
}
@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
print("IOS background"); // Since I am just working with android, I am just ignoring the IOS //function
return true;
}
@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
// Only available for flutter 3.0.0 and later
await Firebase.initializeApp();
DartPluginRegistrant.ensureInitialized();
Timer.periodic(const Duration(seconds: 5), (timer) async {
if (service is AndroidServiceInstance) {
// uname is the variable I retrieve using shared preferences in the main function...
databaseReference.child('Users/${uname}/Panic').onValue.listen((event) {
final boolFlag = event.snapshot.value;
if (boolFlag == true) {
sendNotification();
}
});
}
}
Future<void> sendNotification() async {
const channel = AndroidNotificationChannel(
'Id1',
'Alert notification channel',
importance: Importance.high,
);
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
final notificationDetails = NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
importance: Importance.high,
),
);
await _flutterLocalNotificationsPlugin.show(
0,
'Alert !!!',
'Alert!!! Alert !!!',
notificationDetails,
payload: "Payload",
);
}
Future <void> main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await _firebaseMessaging.requestPermission();
final token = await _firebaseMessaging.getToken();
print('FCM Token: $token');
sharedPreferences = await SharedPreferences.getInstance();
dBr = await FirebaseDatabase.instance.ref();
vals = await keepMeSignedIn();
userName = vals[0] ?? "User";
uname = vals[1];
val = vals[2] ?? false;
print("Details from main page: $userName $uname $val");
await initializeService(); // Initializing the bg service
runApp(
MaterialApp(
home: SplashScreen(uname,val),
debugShowCheckedModeBanner: false,
));
}