Open terminated Flutter app using background notification (Android) - android

I'm building Flutter android app for webrtc calls. When a call is coming I use Firebase Cloud Messages (background data messages) to notify my app. Using callkeep flutter plugin I can show incoming call screen. Everything works grate but I don't know how to open flutter app when it is terminated (not in background). I receive background notification and can run some code (e.g. show local notification, show incoming call screen) but I don't know how to open my app. Any suggestions?

You can use connectycube_flutter_call_kit package after which you can then navigate to the desired screen
ConnectycubeFlutterCallKit.instance.init(
onCallAccepted: (String sessionId, int callType, int callerId,
String callerName, Set opponentsIds
, Map callOpponentsop
) async {
// Navigator.pushNAmed()
return null;
},
onCallRejected: (String sessionId, int callType, int callerId,
String callerName, Set opponentsIds
, Map callOpponents
) {
return null;
},
);

Related

flutter firebase messaging handling clicked notification on background

I'm using the firebase_messaging package on my flutter app and it works perfectly for everything except that when the app on the background and I get a notification it only opens the app and never do what I ask it does after opening the app ..here is my code:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
final dynamic data = message.data;
print("data is $data");
if(data.containsKey('request_id')) {
print("we are inside ..!");
RegExp exp = RegExp(r'\d+');
var id = int.parse(exp.firstMatch(data['request_id']!)!.group(0)!);
OpenRequestsController openRequestsController = Get.isRegistered<OpenRequestsController>()?Get.find():Get.put(OpenRequestsController());
OpenRequest matchingRequest = openRequestsController.openRequestsList.firstWhere((request) => request.id == id);
print("the request from the list is $matchingRequest");
openRequestsController.openRequestDetails(matchingRequest,false);
}
}
what happens here is that it tries to run the whole function when the message is received not when clicked .. and ofc it fails because the app is not already running in the foreground
For opening the application and moving to the said screen you need to implement onMessageOpenedApp in the initstate of your first stateful widget which will let the application to know that it is supposed to open the application when a notification being clicked. The code function should look like this:
FirebaseMessaging.onMessageOpenedApp.listen((message) {
Get.to(() => const MainScreen()); // add logic here
});
It is better if you could assign identifiers for the type of screens you want to open on clicking a particular notification while sending the notification and implement an if-else or switch statement here on the basis of message type.
Thanks

Cancel notification recieved from FireBase client side Android/IOS?

Is it possible to cancel a pushed notification before displaying it on the users phone ?
I have some custom logic which decides whether a notification needs to be displayed/appear . Is it possible for me to control this behaviour from the client side ios/android code ?
Once a message is sent to Firebase Cloud Message, there is no way to cancel its delivery.
If your message contains only a data element and no notification, displaying the message is handled by your application code - so in that case you may be able to suppress its display there.
Although the best way is to handle this is to cancel it on backend side, you still can add UNNotificationServiceExtension and override the didReceive method:
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: #escaping (UNNotificationContent) -> Void) {
self.receivedRequest = request;
self.contentHandler = contentHandler
self.content = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let content = self.content {
// I had to check something inside the push itself
if let infoDictionary = content.userInfo {
// Check something inside the push notification
contentHandler(content)
return
}
}
// Otherwise, send an empty notification to the system and it will show nothing
contentHandler(UNNotificationContent())
}

EXPO Receiving Notifications works when the application is in the background/foreground, but not when the application is killed

I just learned about notifications in the expo, now I have successfully sent notifications and I have also managed to get data from the notifications I sent, the problem is, if the application is in background or foreground, addNotificationResponseReceivedListener is working properly (redirect to another page), but if I close the application, and I receive a notification, then I press the notification, the application opens but the addNotificationResponseReceivedListener function is not running, I try this in a standalone application
what i’m using:
“expo”: “~40.0.0”,
“expo-notifications”: “^0.9.0”,
here’s my example code in Home.js:
componentDidMount() {
//another code..
Notifications.addNotificationResponseReceivedListener(
this._handleNotificationResponse
);
}
_handleNotificationResponse = (response) => {
console.log(
"CONSOLE FROM NOTIF: " +
JSON.stringify(response.notification.request.content.data.from)
);
if (response.notification.request.content.data.from== "GEMASS") {
this.props.navigation.navigate("goToPage", {
//another code...
});
} else {
}
};
here’s my file tree:
App.js
Components
- Home.js
and here’s my terminal looks like when i run on expo client:
clickme
can you guys help me? it means a lot :)

How to handle the tap events in Push Notifications in Xamarin Forms?

I've created the Xamarin Forms PCL project. I've integrated the OneSignal push notifications which are coming and showing fine. I want to handle the event when someone taps on the notification so that I can show the activity corresponding to that. I've also added the Xam.Plugin.Pushnotifications but I can't handle the tap even. The message comes and I can capture the message and play with it but I want to handle the tap event on notifications. How should I do that in PCL?
The Xamarin OneSignal SDK does not support PCL project since it requires platform specific classes. You will need to add your code to shared project as shown in the Xamarin OneSignal setup guide.
Use the following code to handle a notification open event.
// Notification Opened Delegate
OneSignal.NotificationOpened exampleNotificationOpenedDelegate = delegate (OSNotificationOpenedResult result)
{
try
{
System.Console.WriteLine("OneSignal Notification opened:\nMessage: {0}", result.notification.payload.body);
Dictionary<string, object> additionalData = result.notification.payload.additionalData;
if (additionalData.Count > 0)
System.Console.WriteLine("additionalData: {0}", additionalData);
List<Dictionary<string, object>> actionButtons = result.notification.payload.actionButtons;
if (actionButtons.Count > 0)
System.Console.WriteLine("actionButtons: {0}", actionButtons);
}
catch (System.Exception e)
{
System.Console.WriteLine(e.StackTrace);
}
};
OneSignal.StartInit("YOUR_APP_ID", "YOUR_GOOGLE_PROJECT_NUMBER")
.HandleNotificationOpened(exampleNotificationOpenedDelegate)
.EndInit();

Starting Web App on Android from a notification click in a service worker

From the sample code on the Goggle web site I can see how to look for and either focus on or start a url in the Browser on the Android device when a notification is clicked. But what I need to do is look for and either focus or start a Web App that the user has added to their home screen.
This is the sample code from Google to start a url such as https://www.google.co.uk/
self.addEventListener('notificationclick', function (event) {
console.log('Notification click: tag ', event.notification.tag);
event.notification.close();
var url = 'https://www.google.co.uk/';
event.waitUntil(
clients.matchAll({
type: 'window',
})
.then(function (windowClients) {
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
Let’s say that the start url in my Progressive Web App is https://www.myWebApp.co.uk/ , That app is now added to the home screen and has a service worker that listens for the push event. That all works great. I need to adapt the above code to check is that url is running as a web app and focus on it, or if not then start and focus on that app when a notification is clicked .
I have tried changing this to just my URL but it opens a new browser window not my Progressive web app.
Any ideas

Categories

Resources