Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Push notification with Azure notification Hub is working in debug mode but not in release

$
0
0

My App is running on Xamarin.Forms 4.7 for android only and I have followed the instruction given on Microsoft site My App is running on Xamarin.Forms 4.7 for android only and I have followed the instruction given on Microsoft site and push notification work in debug mode on emulator but if I release app and install on real device or emulator, it doesn't work.

Below is my Androidmenifiest:
























    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/Support_Desk_Logo" />

    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />

    <service android:exported="true" android:name="com.bientechnologies.MyFirebaseMessagingService" android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="${applicationId}" />
        </intent-filter>
    </receiver>
    <uses-library android:name="org.apache.http.legacy" android:required="false" />
</application>

Below, is my class which intercepts the notifications:

```[Service(Enabled = true, Exported = true, Name = "com.bientechnologies.MyFirebaseMessagingService")]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public static System.String MyToken = "";
const string TAG = "MyFirebaseMsgService";

public override void OnNewToken(string token)
{
    // NOTE: save token instance locally, or log if desired

    try
    {
        SendRegistrationToServer(token, this);
        if (App.IsUserLoggedIn)
        {
            Task.Run(async () =>
            {

                var service = new Bien.DeskApp.Services.NotificationService();
                await service.SubscribeAsync(App.LoginResponse.Username, token);
            });
        }
    }
    catch (Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}

public static void SendRegistrationToServer(string token, Context context)
{
    try
    {
        NotificationHub hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, context);

        // register device with Azure Notification Hub using the token from FCM
        Registration registration = hub.Register(token, Constants.SubscriptionTags);

        // subscribe to the SubscriptionTags list with a simple template.
        string pnsHandle = registration.PNSHandle;
        TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", Constants.FCMTemplateBody, Constants.SubscriptionTags);
    }
    catch (Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering device: {e.Message}");
    }
}

public override void OnMessageReceived(RemoteMessage message)
{

    try
    {
        Log.Debug(TAG, "From: " + message.From);
        if (message.GetNotification() != null)
        {
            //These is how most messages will be received
            Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
            SendNotification(message.GetNotification().Body);
        }
        else if (message.Data.Values.Any())
        {
            //Only used for debugging payloads sent from the Azure portal
            SendNotification(message.Data.Values.First());
        }
    }
    catch(Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}

void SendNotification(string messageBody)
{
    try
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
        string channelNameAndroid = "Android Channel";

        NotificationChannel androidChannel = new NotificationChannel(Constants.CHANNEL_ID, channelNameAndroid, NotificationImportance.Default);
        androidChannel.EnableVibration(true);
        androidChannel.SetSound(null, null);
        androidChannel.ShouldShowLights();
        androidChannel.EnableLights(true);
        androidChannel.SetShowBadge(true);
        androidChannel.LightColor = Resource.Color.accent_material_light;
        androidChannel.LockscreenVisibility = NotificationVisibility.Public;

        var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
        if (notificationManager == null)
        {
            notificationManager = NotificationManager.FromContext(this);
        }

        notificationManager.CreateNotificationChannel(androidChannel);

        var notificationBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_ID);

        notificationBuilder.SetContentTitle("Bien Desk")
                    .SetSmallIcon(Resource.Drawable.smallicon)
                    .SetLargeIcon(Android.Graphics.BitmapFactory.DecodeResource(Resources, Resource.Drawable.Support_Desk_Logo))
                    .SetContentText(messageBody)
                    .SetAutoCancel(false)
                    .SetShowWhen(true)
                    .SetGroup("biendesk")
                    .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                    .SetContentIntent(pendingIntent);

        // var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
    }
    catch(Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}

private void MountAlert(string title, string message, PendingIntent intent)
{
    try
    {
        string channelIdAndroid = Constants.CHANNEL_ID;
        string channelNameAndroid = "Android Channel";

        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            NotificationChannel androidChannel = new NotificationChannel(channelIdAndroid, channelNameAndroid, NotificationImportance.Default);
            androidChannel.EnableVibration(true);
            androidChannel.SetSound(null, null);
            androidChannel.ShouldShowLights();
            androidChannel.EnableLights(true);
            androidChannel.SetShowBadge(true);
            androidChannel.LightColor = Resource.Color.accent_material_light;
            androidChannel.LockscreenVisibility = NotificationVisibility.Public;

            var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);

            notificationManager.CreateNotificationChannel(androidChannel);

            var notificationBuilder = new Notification.Builder(this, channelIdAndroid)
                            .SetSmallIcon(Resource.Drawable.smallicon)
                            .SetLargeIcon(Android.Graphics.BitmapFactory.DecodeResource(Resources, Resource.Drawable.Support_Desk_Logo))
                            .SetColor(Resource.Color.accent_material_light)
                            .SetContentTitle(title)
                            .SetContentText(message)
                            .SetAutoCancel(true)
                            .SetStyle(new Notification.BigTextStyle().BigText(message))
                            .SetContentIntent(intent);

            notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
        }
    }
    catch (Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}```

Please suggest what I am missing.

thanks and push notification work in debug mode on emulator but if I release app and install on real device or emulator, it doesn't work.

Below is my Androidmenifiest:

```






















    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/Support_Desk_Logo" />

    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />

    <service android:exported="true" android:name="com.bientechnologies.MyFirebaseMessagingService" android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="${applicationId}" />
        </intent-filter>
    </receiver>
    <uses-library android:name="org.apache.http.legacy" android:required="false" />
</application>

```

Below, is my class which intercepts the notifications:

```[Service(Enabled = true, Exported = true, Name = "com.bientechnologies.MyFirebaseMessagingService")]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public static System.String MyToken = "";
const string TAG = "MyFirebaseMsgService";

public override void OnNewToken(string token)
{
    // NOTE: save token instance locally, or log if desired

    try
    {
        SendRegistrationToServer(token, this);
        if (App.IsUserLoggedIn)
        {
            Task.Run(async () =>
            {

                var service = new Bien.DeskApp.Services.NotificationService();
                await service.SubscribeAsync(App.LoginResponse.Username, token);
            });
        }
    }
    catch (Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}

public static void SendRegistrationToServer(string token, Context context)
{
    try
    {
        NotificationHub hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, context);

        // register device with Azure Notification Hub using the token from FCM
        Registration registration = hub.Register(token, Constants.SubscriptionTags);

        // subscribe to the SubscriptionTags list with a simple template.
        string pnsHandle = registration.PNSHandle;
        TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", Constants.FCMTemplateBody, Constants.SubscriptionTags);
    }
    catch (Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering device: {e.Message}");
    }
}

public override void OnMessageReceived(RemoteMessage message)
{

    try
    {
        Log.Debug(TAG, "From: " + message.From);
        if (message.GetNotification() != null)
        {
            //These is how most messages will be received
            Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
            SendNotification(message.GetNotification().Body);
        }
        else if (message.Data.Values.Any())
        {
            //Only used for debugging payloads sent from the Azure portal
            SendNotification(message.Data.Values.First());
        }
    }
    catch(Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}

void SendNotification(string messageBody)
{
    try
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
        string channelNameAndroid = "Android Channel";

        NotificationChannel androidChannel = new NotificationChannel(Constants.CHANNEL_ID, channelNameAndroid, NotificationImportance.Default);
        androidChannel.EnableVibration(true);
        androidChannel.SetSound(null, null);
        androidChannel.ShouldShowLights();
        androidChannel.EnableLights(true);
        androidChannel.SetShowBadge(true);
        androidChannel.LightColor = Resource.Color.accent_material_light;
        androidChannel.LockscreenVisibility = NotificationVisibility.Public;

        var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
        if (notificationManager == null)
        {
            notificationManager = NotificationManager.FromContext(this);
        }

        notificationManager.CreateNotificationChannel(androidChannel);

        var notificationBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_ID);

        notificationBuilder.SetContentTitle("Bien Desk")
                    .SetSmallIcon(Resource.Drawable.smallicon)
                    .SetLargeIcon(Android.Graphics.BitmapFactory.DecodeResource(Resources, Resource.Drawable.Support_Desk_Logo))
                    .SetContentText(messageBody)
                    .SetAutoCancel(false)
                    .SetShowWhen(true)
                    .SetGroup("biendesk")
                    .SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
                    .SetContentIntent(pendingIntent);

        // var notificationManager = NotificationManager.FromContext(this);
        notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
    }
    catch(Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}

private void MountAlert(string title, string message, PendingIntent intent)
{
    try
    {
        string channelIdAndroid = Constants.CHANNEL_ID;
        string channelNameAndroid = "Android Channel";

        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            NotificationChannel androidChannel = new NotificationChannel(channelIdAndroid, channelNameAndroid, NotificationImportance.Default);
            androidChannel.EnableVibration(true);
            androidChannel.SetSound(null, null);
            androidChannel.ShouldShowLights();
            androidChannel.EnableLights(true);
            androidChannel.SetShowBadge(true);
            androidChannel.LightColor = Resource.Color.accent_material_light;
            androidChannel.LockscreenVisibility = NotificationVisibility.Public;

            var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);

            notificationManager.CreateNotificationChannel(androidChannel);

            var notificationBuilder = new Notification.Builder(this, channelIdAndroid)
                            .SetSmallIcon(Resource.Drawable.smallicon)
                            .SetLargeIcon(Android.Graphics.BitmapFactory.DecodeResource(Resources, Resource.Drawable.Support_Desk_Logo))
                            .SetColor(Resource.Color.accent_material_light)
                            .SetContentTitle(title)
                            .SetContentText(message)
                            .SetAutoCancel(true)
                            .SetStyle(new Notification.BigTextStyle().BigText(message))
                            .SetContentIntent(intent);

            notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
        }
    }
    catch (Exception e)
    {
        Log.Error(Constants.DebugTag, $"Error registering token: {e.Message}");
    }
}```

Please suggest what I am missing.

thanks


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>