Firebase Push Notification is Not Received when App is in Foreground - firebase

I am using unity 2018 with Firebase. I am working on Firebase Push Notification.The Push Notification Message is Received well.
But when my run my app running in foreground the push notification message is not received. But when my close my app. The push notification message is received.
What i have to do for Receiving Push Notification when my app is in Foreground?

You have to handle push notification manually in callback:
//Subscribe on application start
public void Start() {
Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
}
public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e)
{
UnityEngine.Debug.Log("Received a new message from: " + e.Message.From);
if (e.Message.NotificationOpened == false)
{
// Show PopUp or Do something here
}
}

Related

Xamarin.Forms push-notifications are transmitted very unreliably (late or not at all)

I am writing an Xamarin.forms based app which is currently running on android platform. It is the first time I need to use push-notifications. I followed a guide from microsoft (https://learn.microsoft.com/de-de/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=vswin)") to implement the notifications.
The target android version is 8.1 API 27. The app runs on a Samsung tab active 2, which has android 8.1.
I configured the app as seen in the tutorial. I push the messages through a defined channel and this channel is subscribed in the app. The messages are pushed by a server which triggers the rest call for the FCM api. The first day I did some tests the transmission worked very good and I would say it was (nearly) reliable.
The next day I implemented some other features and wanted to test the push notifications again. Then: I was very confused, the most messages were not delivered or VERY VERY late. I am not sure if all messages were transmitted, there went may be some lost.
For me the FCM service is a big blackbox where I can delegate some work and then I need to hope that the messages will be transmitted. I am very confused now.
I paste here some code, but it is nearly what you can find in the tutorial:
My Questions:
What can I do? Is there something to get some more information from the FCM what my messages are currently doing? Or are there some problems with the code?
This is run in the mainActivity:
if (this.IsPlayServicesAvailable())
{
// Creates a notification channel
this.CreateNotificationChannel();
//Console.WriteLine("InstanceID token: " + FirebaseInstanceId.Instance.Token);
// Subscribe to notification token
FirebaseMessaging.Instance.SubscribeToTopic("channel");
Log.Debug(TAG, "Subscribed to remote notifications");
}
This checks if the channel can be created and creates it: (is called in the mainActivity)
private void CreateNotificationChannel()
{
// The app is not running on Android 8.0 or higher
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
// Create a notification channel for publishing notifications
var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
This checks if playServices are available: (also called in mainActivity)
public bool IsPlayServicesAvailable()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.Success)
{
if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
{
Log.Debug(TAG, GoogleApiAvailability.Instance.GetErrorString(resultCode));
}
else
{
Log.Debug(TAG, "This device has no compatible Google Play services APK - Download an APK from the Google Play Store or to enable it in the device's system settings!");
Finish();
}
return false;
}
else
{
Log.Debug(TAG, "Google Play Services are available.");
return true;
}
}
The last snipped is the service to handle a notification and inform the user:
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class CustomFirebaseMessagingService : FirebaseMessagingService
{
// Logging Tag
private static readonly string TAG = "CustomFirebaseMessagingService";
/* Handles data messages and notifications messages if the app is in foreground.
*
* Apps only have 10 seconds in which to handle an incoming Firebase Cloud Message.
* Any work that takes longer than this should be scheduled for background execution using a library such as the 'Android Job Scheduler' or the 'Firebase Job Dispatcher'.
*
*/
public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "Message from: " + message.From);
// If the message data payload is not empty, display a notification
if (message.Data.Count > 0)
{
Log.Debug(TAG, "Data Payload: " + message.Data.ToString());
this.SendNotification(message.Data);
}
}
// Converts the incoming FCM message into a local notification
private void SendNotification(IDictionary<string, string> data)
{
Console.WriteLine("Push Message received");
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
if (data.TryGetValue("message", out string message))
{
foreach (var key in data.Keys)
{
intent.PutExtra(key, data[key]);
}
var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.NotificationIcon)
.SetContentTitle("TITEL")
.SetContentText(message)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
}
}
}

Show IconBadgeNumber after push notification while app background or closed (Xamarin.iOS)

In my Xamarin.iOS project I use Azure Notification Hub to send push notification to my application.
I can control my IconBadgeNumber with this code in AppDelegate class.
var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Badge, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
I can count number of my push notification when they come:
public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
ProcessNotification(userInfo, false);
UIApplication.SharedApplication.ApplicationIconBadgeNumber = UIApplication.SharedApplication.ApplicationIconBadgeNumber + 1; ;
}
But it will work only if my application is opened. How I can count push notifications for IconBadgeNumber when my app is backgrouned or close?
The count of push notifications is up to your settings in the push service.Such as
Message message = Message.builder()
.setApnsConfig(ApnsConfig.builder()
.putHeader("apns-priority", "10")
.setAps(Aps.builder()
.setAlert(ApsAlert.builder()
.setTitle("$GOOG up 1.43% on the day")
.setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
.build())
.setBadge(42)
.build())
.build())
.setTopic("industry-tech")
.build();
You can set the number of badge setBadge(xxx).

Firebase APN notification are not in the tray when app is in the background

For some reason notifications sent via Firebase don't get in the tray when the app is in the background. Here's the code that initialises Firebase (we're currently testing on iOS 10 using Xamarin in VS 2017). In AppDelegate.cs:
public void InitFirebase()
{
// Configure Firebase
App.Configure();
// Register your app for remote notifications.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10 or later
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
{
Log.Info("BoaTan", "RequestAuthorization: {0}", granted);
});
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = this;
// For iOS 10 data message (sent via FCM)
Firebase.CloudMessaging.Messaging.SharedInstance.RemoteMessageDelegate = this;
// Monitor token generation
InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
{
Log.Info("BoaTan", "New firebase token received {0}", PlatformEntrance.Token);
LoginViewModel viewModel = LoginView.Me.ViewModel as LoginViewModel;
viewModel.UpdateFirebaseToken(PlatformEntrance.Token);
});
Firebase.CloudMessaging.Messaging.SharedInstance.Connect(error =>
{
if (error != null)
{
Log.Error("BoaTan", error.DebugDescription);
}
else
{
Log.Info("BoaTan", "Connection to Firebase messaging succeeded");
}
});
// Monitor token generation
InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
{
SendTokenToServer();
});
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
In the AppDelegate.cs we also have the following code to receive the messages:
public override void WillEnterForeground(UIApplication application)
{
Firebase.CloudMessaging.Messaging.SharedInstance.Connect((NSError error) =>
{
Log.Info("BoaTan", "WillEnterForeground: Connected to Firebase messaging ({0})", error?.Description);
});
base.WillEnterForeground(application);
}
public override void DidEnterBackground(UIApplication application)
{
Firebase.CloudMessaging.Messaging.SharedInstance.Disconnect();
Log.Info("BoaTan", "DidEnterBackground: Disconnected from Firebase messaging");
base.DidEnterBackground(application);
}
// To receive notifications in foregroung on iOS 9 and below.
// To receive notifications in background in any iOS version
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
Log.Info("BoaTan", "DidReceiveRemoteNotification: Disconnected from Firebase messaging");
SendDataMessage(userInfo);
}
// To receive notifications in foreground on iOS 10 devices.
[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
Log.Info("BoaTan", "WillPresentNotification: Disconnected from Firebase messaging");
SendDataMessage(notification.Request.Content.UserInfo);
}
public void ApplicationReceivedRemoteMessage(RemoteMessage message)
{
SendDataMessage(message.AppData);
}
/// <summary>
/// Use MvvmCross messaging to send a message to subcribers.
/// </summary>
/// <param name="dictionary"></param>
private void SendDataMessage(NSDictionary dictionary)
{
LogReceivedInfo(dictionary);
NSObject data;
NSString key = new NSString("data");
if (dictionary.TryGetValue(key, out data))
{
Log.Info("BoaTan", "Data: {0}", data);
Settings.Notification = JsonConvert.DeserializeObject<LoginNotificationParameter>((NSString)data);
ServicesHelper.SendMessage(this);
}
}
private void LogReceivedInfo(NSDictionary keyvalues)
{
Log.Info("BoaTan", "-----------------------------------------------------------");
foreach (var keyval in keyvalues)
{
Log.Info("BoaTan", "Key: {0} Value: {1}", keyval.Key, keyval.Value);
}
Log.Info("BoaTan", "-----------------------------------------------------------");
}
}
Message arrive perfectly when the App is in the foreground. All messages are queued until the App gets in the Foreground again.
This is in the info.plist:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
<string>fetch</string>
</array>
When I go to the Firebase console and compose a message there in several variants the messages also don't arrive in the tray which leads me to the following conclusions:
The App is missing some configuration telling iOS I'm expecting messages.
Something missing is the configuration of APN at the Apple developer console.
Something missing in the Firebase/iOS configuration/initialization.
The permutations are endless. Who has the answer? And then there is still the challenge of iOS 9.
I have no experiences with Firebase on iOS but on Android I had the same problem.
Firebase has two types of messages: Notification message and Data message, see About FCM Messages
On Android the Notification message is only visible when the app is in foreground. Maybe this is also your problem
Don't know exactly why it started working but it works now. After deleting the App from my iPad and reinstalling it the tray started working too. My guess is that a redeploy keeps setting as they are and after a reinstall these were set correctly.

PushNotification with custom parameter from android to IOS goes as just text

notification screenshot on IOS Hi I have been trying to send push-notification from android to ios with custom parameters required for my app. Tried sending it as hashmap as in the code above but did not receive that notification at all instead received default notification as :"you have 1 unread message".Also tried sending it as json(Please refer code ) but it goes as plain text and is displayed as json text in the notification to user as shown in the screen shot attached. Please help me with this so i can send notification with only "message" part displayed to user and other custom parameters to be used internally by app.
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(userId1);
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.APNS);
JSONObject json = new JSONObject();
JSONObject json1 = new JSONObject();
try {
// standart parameters
json.put("text", message);
// custom parameters
json1.put("sellerName", sellerName);
json1.put("Buyer Name", buyerName);
json1.put("Type",type);
json.put("custom",json1 );
} catch (Exception e) {
e.printStackTrace();
}
//HashMap<String, Object> data = new HashMap<String, Object>();
//data.put("message", message);
// data.put("sellerName",sellerName);
//data.put("Type", type);
//event.setMessage(data);
event.setMessage(json.toString());
QBPushNotifications.createEvent(event).performAsync(new QBEntityCallback<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
System.out.println("QBPush Message success"+qbEvent.getMessage());
}
#Override
public void onError(QBResponseException e) {
// System.out.println(" QB Error in Push Message success");
e.printStackTrace();
}
});
If you need to send the universal push notification (the one that goes to all platforms, not only iOS or Android) then you need to omit PushType:
event.setPushType(QBPushType.APNS);
From doc:
https://quickblox.com/developers/Messages#Create_event
event[push_type]:
If not present - Notification will be delivered to all possible
devices for specified users.
If specified - Notification will be delivered to specified platform only
You can refer push notifications code sample page to receive more code snippets (Universal push notifications -> With custom parameters): https://quickblox.com/developers/SimpleSample-messages_users-android#Universal_push_notifications

GCM push notifications for android devices are not working on MI and Letv mobiles

We are facing the problem in sending GCM push notifications to all the android devices. We are developing an app on Ionic platform and using the plugin called cordova push for the push notifications. The device is registering with gcm and receiving device token. I am using 3 devices to test Moto g4 plus, MI4 and Letv.
The problem is push notification is reaching to moto g4 plus device but not to MI and Letv devices when the app is killed. MI and Letv devices are also receiving the notification only when the app is in the foreground or background.
I am receiving delivery receipts from gcm as delivered to all the devices in the app killed case too.
Please suggest some solution to overcome this problem. Thank you.
I also faced this issue
I have Xiaomi mobile that needs 'Autostart Permission' to receive FCM Notification when app is killed,you need to move your app in this list.
For Xiaomi device you can ask user for this permission
Check the answer here
String xiaomi = "Xiaomi";
final String CALC_PACKAGE_NAME = "com.miui.securitycenter";
final String CALC_PACKAGE_ACITIVITY = "com.miui.permcenter.autostart.AutoStartManagementActivity";
if (deviceManufacturer.equalsIgnoreCase(xiaomi)) {
DisplayUtils.showDialog(activity, "Ask for permission", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
Intent intent = new Intent();
intent.setComponent(new ComponentName(CALC_PACKAGE_NAME, CALC_PACKAGE_ACITIVITY));
activity.startActivity(intent);
} catch (ActivityNotFoundException e) {
Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
} catch (Exception e) {
Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
}
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
}
And as for Letv mobile i haven't checked it.If you have solved it then do tell me.

Resources