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

Push Notification using Firebase not showing the Notification

$
0
0

i have followed the documentation https://docs.microsoft.com/en-gb/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=macos in order to implement a simple push notification to my Xamarin.Android app (which is a part of my CrossPlatform Project).

i have succeeded in loading google-Service.json file (confirmed by the getting google App Id logged in output windows as suggested by above documentation) and i Got Instance Device Token ID( Same as that of documentation ) as well .

But when i tried sending my first notification from firebase console im not receiving the notification as per the documentation.Im new in xamarin, so im following exactly what the documentation suggested.

As per my investigation, i get some issue in my Notification Channel Creation as when im creating notificationManager im getting a warning "> java.securityException: Notification policy access Denied" .So i have added manually doing this.But in that it shows "> do not disturb" toggle for my app is already switched off.Even i have added ACCESS_NOTIFICATION_POLICY_SETTING,SET_WALLPAPER permissions to my Android Manifest.
still Im getting same warning of "Notification policy access Denied".

Also when i have checked in my Notification setting of my device .It shows the time of last notification as "just now" whenever i tried sending message directly from firebase console.

Here Im adding My code and Pictures of above issue for more understanding.

MainActivity.cs :

using System;
using Android.Gms.Common;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Plugin.Permissions;
using Android.Content;
using Android.Speech;
using Xamarin.Forms;
using Firebase.Iid;
using Android.Util;

 public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity,IMessageSender
    {
        private readonly int VOICE = 10;
        static readonly string TAG = "MainActivity";

        internal static readonly string CHANNEL_ID = "my_notification_channel";
        internal static readonly int NOTIFICATION_ID = 100;

        TextView msgText;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);

            base.OnCreate(savedInstanceState);
            ZXing.Net.Mobile.Forms.Android.Platform.Init();
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            LoadApplication(new App());


            Log.Debug(TAG, "google app id: " + GetString(Resource.String.google_app_id));
           // SetContentView(Resource.Layout.Main);
            msgText = FindViewById<TextView>(Resource.Id.msgText);

           // var logTokenButton = FindViewById<Android.Widget.Button>(Resource.Id.logTokenButton);
           // logTokenButton.Click += delegate {
                Log.Debug(TAG, "InstanceID token: " + FirebaseInstanceId.Instance.Token);
            //};

            if (Intent.Extras != null)
            {
                foreach (var key in Intent.Extras.KeySet())
                {
                    var value = Intent.Extras.GetString(key);
                    Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
                }
            }
            IsPlayServicesAvailable();

            CreateNotificationChannel();

            // PushNotificationManager.ProcessIntent(this, Intent);
        }


        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);
            if (intent != null)
            {
                var args = intent.GetStringExtra("args");
               // startActivityForResult(new Intent(Android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS), 0);
                //PushNotificationManager.ProcessIntent(this, intent);
            }
        }


public bool IsPlayServicesAvailable()
        {
            int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.Success)
            {
                if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
                    msgText.Text = GoogleApiAvailability.Instance.GetErrorString(resultCode);
                else
                {
                   // msgText.Text = "This device is not supported";
                    Finish();
                }
                return false;
            }
            else
            {
                //msgText.Text = "Google Play Services is available.";
                return true;
            }
        }

        [Obsolete]
        void CreateNotificationChannel()
        {
            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;
            }

            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 notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
            if (notificationManager.IsNotificationPolicyAccessGranted)
            {
               // AudioManager audioManager = (AudioManager)GetSystemService(Context.AudioService);
               // audioManager.SetStreamMute(AudioManager.RingerModeChangedAction);
            }
            else
            {

                // Ask the user to grant access
                // Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                //StartActivity(intent);
                //var intent = new Android.Content.Intent(Android.Provider.Settings.ActionNotificationPolicyAccessSettings);
               // intent.AddFlags();
                Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionNotificationPolicyAccessSettings));
            }

            notificationManager.CreateNotificationChannel(channel);
        }

    }


}

Android Manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="9" android:versionName="1.9" package="com.tps.ekontent" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="28" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
    <uses-permission android:name="android.permission.SET_WALLPAPER" />
    <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" />
    <uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
    <application android:label="AppName" android:icon="@drawable/header_logo" android:roundIcon="@drawable/header_logo" icon="@drawable/icon" android:supportsRtl="true" android:usesCleartextTraffic="true">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
        <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>
    </application>
</manifest>

MyFireBaseMessagingService

using System;
using System.Globalization;
using Android.App;
using Android.Content;
using System.Linq;
using Firebase.Messaging;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.OS;
using static Android.App.ActivityManager;
using Android.Support.V4.App;
using Android.Util;

namespace App.Droid
{

        [Service]
        [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
        public class MyFirebaseMessagingService : FirebaseMessagingService
        {
            const string TAG = "MyFirebaseMsgService";
            public override void OnMessageReceived(RemoteMessage message)
            {
                Log.Debug(TAG, "From: " + message.From);

            var body = message.GetNotification().Body;
            Log.Debug(TAG, "Notification Message Body: " + body);
            SendNotification(body, message.Data);
        }


           void SendNotification(string messageBody, IDictionary<string, string> data)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        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)

                                  .SetContentTitle("FCM Message")
                                  .SetContentText(messageBody)
                                  .SetAutoCancel(true)
                                  .SetContentIntent(pendingIntent);

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
    }
        }


}

MyFireBaseIIDService

    using System;
    using Android.App;
    using Firebase.Iid;
    using Android.Util;

    namespace App.Droid
    {
        [Service]
        [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
        public class MyFirebaseIIDService : FirebaseInstanceIdService
        {
            const string TAG = "MyFirebaseIIDService";
            public override void OnTokenRefresh()
            {
                var refreshedToken = FirebaseInstanceId.Instance.Token;
                Log.Debug(TAG, "Refreshed token: " + refreshedToken);
                SendRegistrationToServer(refreshedToken);
            }
            void SendRegistrationToServer(string token)
            {
                // Add custom implementation, as needed.
            }
        }
    }

Warining in NotificationManager during NAtification Channel Creation

Firebase Notification Dashboard

In my Device Notification Settings

if any further information needed,Please let me Know
Any suggestions will be appreciated.Thanks in Advance


Viewing all articles
Browse latest Browse all 204402

Trending Articles



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