yako-dev / flutter-status-alert

Display Apple system-like self-hiding status alerts. It is well suited for notifying user without interrupting user flow.
https://pub.dev/packages/status_alert
Apache License 2.0
131 stars 9 forks source link

How to run StatusAlert.show() in background #3

Closed Chethansmash7 closed 3 years ago

Chethansmash7 commented 4 years ago

I want to display a alert notification using StatusAlert.show(.........) in Flutter.The problem is I can run it foreground(it can be shown only over the current build context) but I want to run the StatusAlert's notification in background.The Alert is actually called when a countdown timer reaches zero.Can anyone suggest me how.

import 'package:android_alarm_manager/android_alarm_manager.dart'; import 'package:flutter/material.dart'; import 'package:flutter_datetime_picker/flutter_datetime_picker.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:intl/intl.dart'; import 'package:flushbar/flushbar.dart'; import 'package:status_alert/status_alert.dart'; import 'CommonPicker.dart'; import 'fileUtils.dart'; import 'package:firebase_messaging/firebase_messaging.dart';

Future myBackgroundMessageHandler(Map<String, dynamic> message) { if (message.containsKey('data')) { // Handle data message final dynamic data = message['data']; }

if (message.containsKey('notification')) { // Handle notification message final dynamic notification = message['notification']; }

// Or do other work. }

void status_bar() {

StatusAlert.show( context, blurPower: 0.1, duration: Duration(seconds: 5), title: 'Hey', subtitle: 'Message:XXXXXXXXXXXXXXXXXXXXXXXXXX ', configuration: IconConfiguration(icon: Icons.warning), ); } // //FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); // //initializeNotification()async { // var initializeAndroid = AndroidInitializationSettings( // 'ic_launcher'); // var initializeIOS = IOSInitializationSettings(); // var initSettings = InitializationSettings(initializeAndroid, initializeIOS); // await flutterLocalNotificationsPlugin.initialize(initSettings); //} // //Future singleNotification(DateTime dateTime,String message,String subtext,int hashcode,{String sound}) async { // var androidChannel = AndroidNotificationDetails( // 'channel-id', 'channel-name', 'channel-description', // importance: Importance.Max, priority: Priority.Max,enableVibration: true,visibility:NotificationVisibility.Public ); // var iosChannel = IOSNotificationDetails(); // var platformChannelSpecifics = NotificationDetails(androidChannel, iosChannel); // await flutterLocalNotificationsPlugin.show(0, message, subtext, platformChannelSpecifics,); //}

Future callback() async { print("I am in the isolate");

// DateTime now=DateTime.now().toLocal();

status_bar();

// await singleNotification(now, "notification" , "This is the message", 98123871); print("last line of Isolate"); }

class AlertTime2 extends StatefulWidget { static const routeName = '/alertTime2';

@override _AlertTime2State createState() => _AlertTime2State(); }

class _AlertTime2State extends State { String mm = "00"; String ss = "00"; var mmValue; var ssValue; var totalTimeInSec; Flushbar flush; String _selectedTime;

final FirebaseMessaging _messaging = FirebaseMessaging();

@override void initState() { super.initState();

//initializeNotification();

_messaging.getToken().then((token) {
  print("token is :" + token);
});

FileUtils().readFromFile().then((String value) {
  setState(() {
    _selectedTime = value;
  });
});

}

// ignore: non_constant_identifier_names void display_flush_bar() { Future.delayed(Duration(seconds: totalTimeInSec), () { setState(() { flush = Flushbar( title: "Hey", message: "XXXXXXXXXXXXXXXXXXXXxx", duration: Duration(seconds: 5), isDismissible: true, icon: Icon( Icons.warning, color: Colors.red, ), dismissDirection: FlushbarDismissDirection.HORIZONTAL, mainButton: FlatButton( onPressed: () { flush.dismiss(true); }, child: Text( "CANCEL", style: TextStyle(color: Colors.amber), ), ), )..show(context); }); }); }

void alarm_managing_function(int t) async { await AndroidAlarmManager.initialize(); await AndroidAlarmManager.periodic(Duration(seconds: t), 0, callback); }

@override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(30, 70, 0, 0), child: Text( "Timer for Notification", style: TextStyle( fontSize: 50, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 150, 0, 0), child: Text( "MM-SS", style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 0, 0, 0), child: Text( "${_selectedTime ?? 'Selected Time'}", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 38), ), ), RaisedButton( onPressed: () { DatePicker.showPicker(context, showTitleActions: true, pickerModel: CustomPicker(currentTime: DateTime.tryParse(_selectedTime)), onConfirm: (time) { setState(() { print(time); _selectedTime = DateFormat("mm-ss").format(time); FileUtils().saveToFile(_selectedTime);

            mm = _selectedTime.substring(0, 2);
            ss = _selectedTime.substring(3, 5);
            print(mm);
            print(ss);
            mmValue = int.parse(mm);
            ssValue = int.parse(ss);
            totalTimeInSec = mmValue * 60 + ssValue;
            print(totalTimeInSec);

            display_flush_bar();
            alarm_managing_function(totalTimeInSec);
          });
        }, locale: LocaleType.en);
      },
      child: Text("Show Time picker"),
    ),
  ],
));

} }

yadaniyil commented 3 years ago

@Chethansmash7 Sorry for the delay. Our plugin is designed to be used in context. It is not intended to be displayed outside the application. But you can try with SystemAlert plugin and maybe you can do something with that.