How to launch an application when Notification Received from flutter app - flutter

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.

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.

Firebase FCM background notifications click_action

i want to navigate to a specific screen route when i click on the background notification
for now the default behavior is just launching my app, so how and where do i change the default behavior of the click action
i'm sending the notification using cloud functions, here is the code
const payload: admin.messaging.MessagingPayload = {
notification: {
title: doc["senderName"],
body: doc["msg"],
sound: "default",
badge: "1",
},
data: {
type: "chat",
},
};
return fcm
.sendToDevice(tokens, payload);
somehow i want to access the type "chat" so from there i can navigate to a chat screen
Use onMessageOpenedApp to handle when a user presses a notification. RemoteMessage has data property which holds the custom parameters.
When you click on the notification from background state, onMessageOpened stream function is called.
Initialize this stream function in the initState of first page of the app and check the data in payload you received from the notification just like this:
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
if (message != null) {
String screenName = message.data['screenName'];
print("Screen name is: $screenName");
if (screenName == 'chat') {
//Navigate to your chat screen here
}
}
});

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())
}

Flutter display a notification for a long time like whatsapp call

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