Flutter display a notification for a long time like whatsapp call - flutter

When i receive a call notification on whatsapp it stays on a screen for a long time.
I am trying to create same behaviour using flutter and FCM notification. I am using below code
I am using same collapseKey but after showing notification two times the notification appear in background and not as heads-up notification.
callNotificationTimer = Timer(Duration(seconds: 8), () {
sendPayLoad(
fcmToken,
collapseKey: collapseKey,
callData: request,
userData: userData,
);
});
sendPayLoad(
fcmToken,
collapseKey: collapseKey,
callData: request,
userData: userData,
);

I highly recommend you to use this package: flutter_incoming_call to display a notification for a long time like whatsapp call

Related

How to handle notification action button clicks in background in Flutter using awesome_notifications?

I am using awesome notifications in Flutter to show local notifications. My plan is to have an action button in a notification, which changes some values in the shared preferences in the background (without opening the app) when pressed. Is this even possible to do?
I tried using onActionReceivedMethod-listener and getInitialNotificationAction-method in my main function after initializing awesome notifications:
AwesomeNotifications().setListeners(onActionReceivedMethod: (action) async{
print(action.body);
});
// OR
ReceivedAction? receivedAction = await AwesomeNotifications().getInitialNotificationAction(
removeFromActionEvents: false
);
if (receivedAction?.body != null){
print(receivedAction.body);
}
Both of them worked (separetly used) only when the app had already started, but they also gave this error:
Awesome Notifications: A background message could not be handled in Dart because there is no dart background handler registered. (BackgroundService:58)
But how I could get it working when the app is not opened? Can I create a backgroung handler without Firebase, or is there some other way to achieve this?
Here is my code, how I create the notification:
static Future<void> createSimpleNotification() async {
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'important_channel',
title: 'Title',
body: 'Test',
largeIcon: 'asset://assets/iconPhoto.png'),
actionButtons: [
NotificationActionButton(
key:'key',
label: 'label',
actionType: ActionType.SilentBackgroundAction)]
);
}
I found the answer from here: Cannot find AwesomeNotifications().actionStream
I implemented it like this:
#pragma("vm:entry-point")
Future<void> _onActionReceivedMethod(ReceivedAction action) async {
print('It works');
}
And it worked both when the app was in the background or in the foreground.

How to get OneSignal playerId (userId) in Flutter?

How to get playerId of a user inside the flutter app?. Player Id can be found in One signal website but i want that inside the flutter app and want to store it to send the notification to particular user.
This is my goto function for initating onesignal
Future<void> initOneSignal(BuildContext context) async {
/// Set App Id.
await OneSignal.shared.setAppId(SahityaOneSignalCollection.appID);
/// Get the Onesignal userId and update that into the firebase.
/// So, that it can be used to send Notifications to users later.̥
final status = await OneSignal.shared.getDeviceState();
final String? osUserID = status?.userId;
// We will update this once he logged in and goes to dashboard.
////updateUserProfile(osUserID);
// Store it into shared prefs, So that later we can use it.
Preferences.setOnesignalUserId(osUserID);
// The promptForPushNotificationsWithUserResponse function will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
await OneSignal.shared.promptUserForPushNotificationPermission(
fallbackToSettings: true,
);
/// Calls when foreground notification arrives.
OneSignal.shared.setNotificationWillShowInForegroundHandler(
handleForegroundNotifications,
);
/// Calls when the notification opens the app.
OneSignal.shared.setNotificationOpenedHandler(handleBackgroundNotification);
}

Flutter Background Service

Hi I'm building a VoIP App in Flutter. I use background_fetch to run a headless task in order to work even if the app is closed. The listener is working, and a notification is sent. But, as the application is closed, the push notification with wake up the app (so home.dart for example) and I would like the push my call screen widget. I see two solution but I don't know how to do it :
the headless task from background_fetch is independent, so I can't transfer my service call data to my app (main) when the user open it, so the call is lost ...
I try to push the right widget (Router.go(/callscreen)) but it's not working.
What can I do in order to fix this ? Thank !
You are using 2 services in background, flutter-local-notification and background-fetch. It's too much. You can use flutter-local-notification in backgound only. Have a look here.
final newRouteName = "callScreen";//Future onSelectNotification(String payload) async
bool isNewRouteSameAsCurrent = false;
Navigator.popUntil(context, (route) {
if (route.settings.name == newRouteName) {
isNewRouteSameAsCurrent = true;
}
return true;
});
if (!isNewRouteSameAsCurrent) {
Navigator.of(context).push(CallScreen())
}

How to show only one notification with FCM and awesome_notifications

I am using Firebase Messaging to send users notifications from the cloud, but I want some notifications to have action buttons options (text input, button selections) from within the notification, so I'm using the awesome_notifications.
I have set up the package to run this method whenever an notification is received:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: 1,
channelKey: 'basic_channel',
title: message.notification.title,
body: message.notification.body,
createdSource: NotificationSource.Firebase,
notificationLayout: NotificationLayout.BigText,
),
actionButtons: <NotificationActionButton>[
NotificationActionButton(
key: 'short_text',
label: 'Answer',
buttonType: ActionButtonType.InputField,
autoCancel: true,
),
],
);
}
This does properly generate a notification with the correct title, body, layout, and text input option, but the notification received directly from FCM is also displayed. I only want the notification that I generate with awesome_notifications to be shown but I can't seem to find a way to do this. Thanks for any input.
Firebase Cloud Messaging(FCM) has two types of messages:
Notification messages in which FCM automatically displays the message to end-user devices on behalf of the client app.
Data messages in which your app is responsible for processing data messages.
About FCM messages
You should use a data message so your app does not display the automatic notification that comes with the notification message type that you currently use.
So if your cloud function contained this code below to send notification messages:
const message = {
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
};
admin.messaging().send(message);
you can update it to:
const message ={
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"title" : "Portugal vs. Denmark",
"body" : "great match!"
}
}
};
admin.messaging().send(message);

How to launch an application when Notification Received from flutter app

I am developing a mobile app and I want to open a splash screen or open startup page when I receive a notification.
Currently, I am using the following code
static Future<dynamic> myBackgroundMessageHandler(
Map<String, dynamic> message) async {
print("_backgroundMessageHandler");
_callBgHandler = 1;
if (message.containsKey('data')) {
// Handle data message
final dynamic data = message['data'];
print("_backgroundMessageHandler: ${data}");
DeviceApps.openApp("com.example.my_flutter_app");
}
if (message.containsKey('notification')) {
// Handle notification message
final dynamic notification = message['notification'];
print("_backgroundMessageHandler notification: ${notification}");
}
return Future<void>.value();
}
and the following error displayed
Attempt to invoke virtual method 'android.content.pm.PackageManager
android.app.Activity.getPackageManager()' on a null object reference
The last one month tried but no luck. If anyone knows let me share the code from flutter dart language
But Button press event it will work.
RaisedButton(
onPressed: () {
DeviceApps.openApp("com.example.my_flutter_app");
},
child: Text("Open App")
)
Default applications like a map, chrome, play store, email app, etc... All are open with no issue but the external app does not open notification background function.