How to get OneSignal playerId (userId) in Flutter? - 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);
}

Related

AWS Pinpoint events delayed and don't trigger journeys

I want to create user journey's using AWS Pinpoint. My mobile app is made with Flutter and using Amplify package to create events)
pubspec.yaml
amplify_flutter: ^0.2.4
amplify_analytics_pinpoint: ^0.2.4
I am calling this method to add the event
Future<void> logLogin(String userId) async {
await addEvent('_app.login', {PinPointAnalyticsKeys.userIdProperty: userId});
}
Future<void> addEvent(String eventName, Map<String, String> properties) async {
AnalyticsEvent event = AnalyticsEvent(eventName);
properties.forEach((key, value) {
event.properties.addStringProperty(key, value);
});
Amplify.Analytics.recordEvent(event: event);
await Amplify.Analytics.flushEvents();
}
Method handling the login:
Future<bool> performLogin(String username, String password) async {
//Code that handle login using email/password => userId
await _pinPoint.logLogin(userId);
}
My test journey: a user from a specific segment who does login should get an email right away.
I am having 2 issues:
Events get added to Pinpoint but after a delay (between 10 and 20min approximatively). Shouldn't it get added right away?
When event gets added (after the delay) no journey does get triggered, so no email sent, and the Pinpoint Journey Metrics doesn't change. What could be the reason?
Thank you all for your assistance, if I missed some details please let me know.

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

Flutter : Strange behavior of Shared Preferences

I have a problem with inconsistent shared preferences value. I will try to describe it as simple as possible.
I'm using Firebase Cloud Messaging for push notifications. When app is in background and notification came in, background handler bellow is invoked.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int counter = (prefs.getInt('badge') ?? 0) + 1;
prefs.setInt('badge', counter).then((bool success) {
print(counter);
});
}
My widget uses WidgetsBindingObserver to determine lifecycle state. When I enter the app, state of that widget is onResume and there I want to read that badge value from shared preferences like this.
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int counter = (prefs.getInt('badge') ?? 0);
print(counter);
}
}
Scenario 1:
App opened, notification came in - set badge field to 1.
App in background, notification came in - background handler set badge field to 2.
App resumed, read that badge field, it's still 1.
Scenario 2:
App opened, notification came in - set badge field to 1.
App in background, notification came in - background handler set badge field to 2.
App in background, notification came in - background handler set badge field to 3.
App resumed, read that badge field, it's still 1.
Question: Any idea why field isn't updated?
SharedPreferences can be used on background events handlers. The problem is that the background handler run in a different isolate so, when you try to get a data, the shared preferences instance is empty. To avoid this you simply have to force a refresh:
SharedPreferences prefs= await SharedPreferences.getInstance();
await prefs.reload();
final int counter = (prefs.getInt('badge') ?? 0);
In the same mode, if the shared preferences can be modified in a background hadler, be sure you call this "reload" function in the main isolate when you try to read from theirs.
SharedPreferences or any other local storage won't work in the _firebaseMessagingBackgroundHandler.
You should capture it on getInitialMessage or onMessageOpenedApp.
https://firebase.flutter.dev/docs/messaging/notifications/
TL;DR:
getInitialMessage gets triggered when the application is opened from a terminated state. While onMessageOpenedApp gets triggered when the application is opened from background state.
FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage message) {
if (message != null) {
Navigator.of(context).pushNamed('/messages', arguments: message.data);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
if (message != null) {
Navigator.of(context).pushNamed('/messages', arguments: message.data);
}
});

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.