Push Notification with Firebase not working

sylmosssylmoss BRMember ✭✭

Hi, I think already did everything that is necessary to use firebase remote push notification. I get the token but when I send a message from Firebase Console nothing happens in the client device. The OnMessageReceived is never trigged, even when the app is foreground.

My google_app_id is different from the mobilesdk_app_id in the google_service.json , is that right ?

I'm testing on emulator with Android 7.1.1 API Level 25, Google APIs Intel Atom (x86).

I created MyFirebaseIIDService.cs and MyFirebaseMessagingService.cs based on examples that I found, filled the AndroidManifest.xml file with the receiver tags. Am I missing something?

Thanks

Best Answer

«1

Answers

  • BerayBentesenBerayBentesen TRUniversity ✭✭✭✭

    @sylmoss I wasn't able too make it work but works great on native Android well. I think libraries still need to be updated.

  • gtlealgtleal BRMember ✭✭
    Accepted Answer

    I agree with you @BerayBentesen. @sylmoss, have you heard about OneSignal? I use it in my apps and it works fine.

  • sylmosssylmoss BRMember ✭✭

    I will try to use GCM now. I agree with @BerayBentesen, the libraries need to be updated.
    If I don't manage to get GCM working I will try OneSignal. I need to get this working!! Thank you both!

  • BerayBentesenBerayBentesen TRUniversity ✭✭✭✭

    I forgot to mention that you can use GCM library with Firebase Console. You can check Microsoft Azure examples for GCM Push with Firebase console.

  • sylmosssylmoss BRMember ✭✭

    @felpudo I'll try to use OneSignal now. Wish me luck!

  • DanielVartdalDanielVartdal USMember ✭✭

    Hi guys, could you give me a short review of onesignal @sylmoss @felpudo. I've managed to get both Firebase and Azure notification hubs to work, but would love to hear if onesignal has any game-changer on why I should use it!

    Thanks in advance!

  • sylmosssylmoss BRMember ✭✭

    @DanielVartdal I couldn't get OneSignal working either :/ I must be doing something wrong, but I can't find what.

  • DanielVartdalDanielVartdal USMember ✭✭

    @sylmoss I had some troubles in the start too, but eventually I could receive data from Firebase (switched to notification hubs(Azure) now though). I do believe it had something to do with not having the correct package name on my app.

    As I read, you were using the GCM library right? I don't have my code-base at work, but I could look into it when I get back, to see if I can trigger a direct connection with Firebase with my setup. And then show you how I did it.

    I also see that you use the emulator, I remember reading that if you want to use the emulator, you will need to login with your google account on the emulator to make it work.

    See this link: https://developer.xamarin.com/guides/android/application_fundamentals/notifications/remote-notifications-with-gcm/#Google_Play_Store

    Also check the package name on your app.

  • LeeMorrisLeeMorris USMember ✭✭

    @DanielVartdal, I had problems getting Azure Notification Hubs to work. Can you point me to the instruction or tutorial you followed. Which Nuget packages did you use? I ran into conflicts between versions of the Firebase plugin and the Xamarin Android Support Library. Thanks

  • DanielVartdalDanielVartdal USMember ✭✭

    Hi @LeeMorris . One of the tutorials I followed was this: https://docs.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm

    I see you are also using firebase plugin, that one I haven't tested. For the notification hub, I used the GCM Client plugin which you can find on nuget.

    In the first steps, you connect your Firebase-account with Azure notification hub, and then use Notification hub to send your messages, not Firebase. They have two different endpoints. But if you want to use Firebase only, I also think you can use the GCM package from nuget.

  • gtlealgtleal BRMember ✭✭
    edited January 2017

    Hi @DanielVartdal. Check this link, They explain pretty well the advantages of OneSignal.

  • DanielVartdalDanielVartdal USMember ✭✭

    Hi @gtleal . Thank you for your feedback:)

    As they deliver the service, they have to write as good as they can about it (of course) themselves.

    Do you have any hands-on experience with One Signal? Example on use cases that has fitted your needs by using them?

    Thanks in advance.

  • LeeMorrisLeeMorris USMember ✭✭

    @DanielVartdal, Thanks!, that worked for me.

  • LeeMorrisLeeMorris USMember ✭✭

    Regarding OneSignal, I would review their Privacy policy and make sure I was ok with the data collected.

  • gtlealgtleal BRMember ✭✭

    Hi @DanielVartdal, sorry for the delay. I agree with you, they have to write well about themselves :D. I work on a project that is being implemented on two platforms (mobile and web), when I heard about OneSignal I created some examples to test their features and I was surprised by the ease of implementation (compared to native implementations). In addition to this facility, the control panel they provide us with is complete. So, they fit perfectly to my needs. I believe that if you want some game change, it's worth trying.

    Here goes more articles:
    https://techcrunch.com/2015/04/20/onesignal/
    http://blog.rapidapi.com/2016/12/29/onesignal-api-profile-add-push-notifications/ (This is a nice one)
    http://www.codemag.com/Article/1609051

  • gdeglingdeglin USMember

    I'm on of the developers of OneSignal. Glad to hear it's working well for many of you!

    If you're running to any difficulties, please get in touch with our team via the on-site chat or [email protected] and we'll do our best to help. I'll try to keep an eye on this thread as well.

  • DanielVartdalDanielVartdal USMember ✭✭

    @LeeMorris : Glad it worked out. I'm currently working on a project with push notifications (first time), so if you want to share ideas and how to's just give me a note :)

    Thank you for the feedback on OneSignal.

  • DanielVartdalDanielVartdal USMember ✭✭

    @gtleal : Thanks for the feedback, I'll surely read about it :)

  • sylmosssylmoss BRMember ✭✭
    edited January 2017

    Trying to use OneSignal here. My app gets de token and UserID like it should, and it is recognized in the OneSignal console when I run in the Android Emulator, the notification is "Delivered" but I still can't get any of it on the emulator.

    I'm using enterprise wifi, I'm starting to think this is the problem.

    Ps: I have an active google account logged in the emulator android.

  • sylmosssylmoss BRMember ✭✭

    I managed to get OneSignal working, and it is pretty simple. I couldn't test on emulator, just in an real device. Thanks to @gtleal !

    Now I need to know how to keep the service running even when de app is killed.

  • sylmosssylmoss BRMember ✭✭

    I was comparing my OneSignal solution with Firebase solution and I realize that AndroidManifest with OneSignal has and additional permission, so I added this permission to AndroidManifest using Firebase and the service started to work.

    This is the permission
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

    I delete it and Firebase stopped working again, I put it back and worked perfectly.

  • NoddyNoddy INUniversity
    edited July 2017

    @sylmoss said:
    Hi, I think already did everything that is necessary to use firebase remote push notification. I get the token but when I send a message from Firebase Console nothing happens in the client device. The OnMessageReceived is never trigged, even when the app is foreground.

    My google_app_id is different from the mobilesdk_app_id in the google_service.json , is that right ?

    I'm testing on emulator with Android 7.1.1 API Level 25, Google APIs Intel Atom (x86).

    I created MyFirebaseIIDService.cs and MyFirebaseMessagingService.cs based on examples that I found, filled the AndroidManifest.xml file with the receiver tags. Am I missing something?

    Thanks

    Did you write this code in MainActivity.cs ? @sylmoss I think this will help you.

    var options = new Firebase.FirebaseOptions.Builder()
    .SetApplicationId("firebase app id")
    .SetApiKey("firebase app api key")
    .SetGcmSenderId("firebase app sender id")
    .Build();

            FirebaseApp.InitializeApp(this, options);
    

    And the AndroidManifest.xml will be like

       <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <application android:label="FCMClient" android:icon="@drawable/Icon">
    <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>
    

  • LerrieGLerrieG USMember ✭✭

    @DanielVartdal said:
    Hi guys, could you give me a short review of onesignal @sylmoss @felpudo. I've managed to get both Firebase and Azure notification hubs to work, but would love to hear if onesignal has any game-changer on why I should use it!

    Thanks in advance!

    Hi,
    I've been trying to get Firebase and Azure Notification hub to work for days now using Firebase Messaging but no luck, i feel that i am missing something. I was using Gcm.Client in Azure Notification Hub and it is working fine but I have an issue not getting notification when app is closed.

    Could you give me some advice? Mainly, i just need to make the notification work even when app is close.
    I will probably try the onesignal next. Fingers-cross hope that works.

    Thanks in advance.

  • DanielVartdalDanielVartdal USMember ✭✭

    Hi Lerrie,

    you have got it working when the app is running? Are you able to share some of your code for the GCM?

    -Daniel-

    @LerrieG said:

    @DanielVartdal said:
    Hi guys, could you give me a short review of onesignal @sylmoss @felpudo. I've managed to get both Firebase and Azure notification hubs to work, but would love to hear if onesignal has any game-changer on why I should use it!

    Thanks in advance!

    Hi,
    I've been trying to get Firebase and Azure Notification hub to work for days now using Firebase Messaging but no luck, i feel that i am missing something. I was using Gcm.Client in Azure Notification Hub and it is working fine but I have an issue not getting notification when app is closed.

    Could you give me some advice? Mainly, i just need to make the notification work even when app is close.
    I will probably try the onesignal next. Fingers-cross hope that works.

    Thanks in advance.

  • LerrieGLerrieG USMember ✭✭
    edited August 2017

    @DanielVartdal said:
    Hi Lerrie,

    you have got it working when the app is running? Are you able to share some of your code for the GCM?

    -Daniel-

    Hi Daniel,
    Yes, it is working when the app is running or background and I am using Gcm.Client. But when the app is closed/killed, no notification and I receive error message that the app has stopped working.

    If of any help, this is the error message i receive when i deploy in Google Play:

    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    ... 2 more
    Caused by: android.runtime.JavaProxyThrowable: System.NotSupportedException: Could not activate JNI Handle 0xeed00025 (key_handle 0x420b8ff8) of Java type 'md5feb66ad60a272ca503c0cef49b342a37/MyBroadcastReceiver' as managed type 'CAMobileApp.Droid.MyBroadcastReceiver'.
    System.TypeInitializationException: The type initializer for 'CAMobileApp.Droid.MyBroadcastReceiver' threw an exception. System.NullReferenceException: Object reference not set to an instance of an object
    at CAMobileApp.Droid.MyBroadcastReceiver

  • LerrieGLerrieG USMember ✭✭

    Here is my code.. it is working when the app is open or background but no notification when app is closed/killed.

    MyBroadcastReceiver.cs
    `using Android.App;
    using Android.Content;
    using Android.Util;
    using Gcm.Client;
    using System.Collections.Generic;
    using WindowsAzure.Messaging;
    using Java.Lang;
    using Android.Media;

    namespace CAMobileApp.Droid
    {
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })] // Allow GCM on boot and when app is closed, but seems like not working
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "[MYPACKAGENAMEHERE]" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "[MYPACKAGENAMEHERE]" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "[MYPACKAGENAMEHERE]" })]

    public class MyBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
    {
        public static string[] SENDER_IDS = new string[] { App.client.SenderId };
        public const string TAG = "MyBroadcastReceiver-GCM";
    }
    
    
    [Service] // Must use the service tag
    public class PushHandlerService : GcmServiceBase
    {
        public static string RegistrationID { get; private set; }
        private NotificationHub Hub { get; set; }
    
        public PushHandlerService() : base(App.client.SenderId)
        {
            Log.Info(MyBroadcastReceiver.TAG, "PushHandlerService() constructor");
        }
    
        protected override void OnRegistered(Context context, string registrationId)
        {
            Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
    
            RegistrationID = registrationId;
    
            Hub = new NotificationHub(App.client.NotiHubPath, App.client.NotiHubConnectionStringListen,
                                        context);
            try
            {
                Hub.UnregisterAll(registrationId);
            }
            catch (Exception ex)
            {
                Log.Error(MyBroadcastReceiver.TAG, ex.Message);
            }
    
            var tags = new List<string>() { };
    
            try
            {
                var hubRegistration = Hub.Register(registrationId, tags.ToArray());
            }
            catch (Exception ex)
            {
                Log.Error(MyBroadcastReceiver.TAG, ex.Message);
            }
        }
    
    
    
        protected override void OnMessage(Context context, Intent intent)
        {
            Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");
    
            var title = "Update";
    
            var msg = new Dictionary<string, string>();
    
            if (intent != null && intent.Extras != null)
            {
                foreach (var key in intent.Extras.KeySet())
                {
                    msg[key] = intent.Extras.Get(key).ToString();
                    System.Console.WriteLine("Key " + intent.Extras.Get(key).ToString());
                }
            }
    
            string Message = msg["message"];
    
            //Store the message
            var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private);
            var edit = prefs.Edit();
            edit.PutString("last_msg", msg.ToString());
            edit.PutString("NotificationMessage", Message);
            edit.PutString("NotificationTitle", title);
            edit.Commit();
            if (Message != "")
            {
                createNotification(title, Message);
            }
    
        }
    
        void createNotification(string title, string desc)
        {
    
    
            #region Perfrences
            var prefs = Xamarin.Forms.Forms.Context.GetSharedPreferences(Xamarin.Forms.Forms.Context.PackageName, FileCreationMode.Private);
            string nmsg = prefs.GetString("NotificationMessage", "");
            string ntitle = prefs.GetString("NotificationTitle", "");
    
            #endregion
    
            var UI_Intent = new Intent(this, typeof(MainActivity));
            UI_Intent.PutExtra("MyData", "MainActivity");
    
            Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
            stackBuilder.AddNextIntent(UI_Intent);
    
            PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
            Notification.Builder builder = new Notification.Builder(this)
            .SetAutoCancel(true) // Remove the notification once the user touches it
            .SetContentTitle(ntitle)
            .SetTicker(ntitle)
            .SetContentIntent(resultPendingIntent)
            .SetContentText(nmsg)
            .SetSmallIcon(Droid.Resource.Drawable.icon)
            .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
    
            Notification notifications = builder.Build();
            NotificationManager notificationsManager = GetSystemService(Context.NotificationService) as NotificationManager;
            notificationsManager.Notify(0, notifications);
    
        }
    
    protected override void OnUnRegistered(Context context, string registrationId)
        {
            Log.Verbose(MyBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId);
    
        }
    
        protected override bool OnRecoverableError(Context context, string errorId)
        {
            Log.Warn(MyBroadcastReceiver.TAG, "Recoverable Error: " + errorId);
    
            return base.OnRecoverableError(context, errorId);
        }
    
        protected override void OnError(Context context, string errorId)
        {
            Log.Error(MyBroadcastReceiver.TAG, "GCM Error: " + errorId);
        }
    
    }
    

    }`

    MainActivity.cs
    `public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
    public static MainActivity instance;
    const string TAG = "MainActivity";

        protected override void OnCreate(Bundle bundle)
        {
            instance = this;
    
            base.OnCreate(bundle);
    
            global::Xamarin.Forms.Forms.Init(this, bundle);
    
            //get page height
            DeviceScreenSize devicess = FileHelper.GetDeviceSizePx();
    
            string text = Intent.GetStringExtra("MyData") ?? "Data not available";
            if (text == "MainActivity")
            {
                ShowAlert();
    
            }
    
            LoadApplication(new CAMobileApp.App(dbPath, devicess));
    
            RegisterWithGCM();
    
    
        }
    
    
    
        private void RegisterWithGCM()
                {
                    try
                    {
    
    
                        // Check to ensure everything's set up right
                        GcmClient.CheckDevice(this);
                        GcmClient.CheckManifest(this);
    
                        // Register for push notifications
                        Log.Info("MainActivity", "Registering...");
                        GcmClient.Register(this, App.client.SenderId);
    
    
            }
                    catch (Java.Net.MalformedURLException)
                    {
                        CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Notification Error");
                    }
                    catch (Exception e)
                    {
                        CreateAndShowDialog(e.Message, "Notification Error");
                    }
                }
    
                private void CreateAndShowDialog(String message, String title)
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    
                    builder.SetMessage(message);
                    builder.SetTitle(title);
                    builder.Create().Show();
                }
    
        /// <summary>
        /// Shows the alert for notification.
        /// </summary>
        /// <returns>The notification alert.</returns>
                public void ShowAlert()
                {
                    var prefs = Xamarin.Forms.Forms.Context.GetSharedPreferences(Xamarin.Forms.Forms.Context.PackageName, FileCreationMode.Private);
                    string nmsg = prefs.GetString("NotificationMessage", "");
                    string ntitle = prefs.GetString("NotificationTitle", "");
    
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.SetTitle(ntitle);
                    alert.SetMessage(nmsg);
                    alert.SetPositiveButton("OK", (senderAlert, args) =>
                    {
                        alert.Dispose();
                    });
    
                    RunOnUiThread(() =>
                    {
                        alert.Show();
                    });
                }
    }`
    

    AndroidManifest.xml
    < ?xml version="1.0" encoding="utf-8"? > < manifest ...... ..... > < uses-sdk android:minSdkVersion="15" / > < application android:icon="@drawable/icon" > < / application> < uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" / > < uses-permission android:name="android.permission.ACCESS_WIFI_STATE" / > < uses-permission android:name="android.permission.GET_ACCOUNTS" / > < uses-permission android:name="android.permission.INTERNET" / > < uses-permission android:name="android.permission.WAKE_LOCK" / > < uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" / > < uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" / > < uses-permission android:name="[MYPACKAGENAMEHERE].permission.C2D_MESSAGE" / > < permission android:name="[MYPACKAGENAMEHERE].permission.C2D_MESSAGE" android:protectionLevel="signature" /> < / manifest >

  • JuanVDJuanVD MXMember

    Lerrie, I'm not an expert in xamarin, Actually I'm begining but when this happened to me in Android Studio, it was because of the type of notification I was sending from my backend, not all the notifications have the same body, I will take a look and let you know what was the change i did!

  • DanielVartdalDanielVartdal USMember ✭✭

    Have you tried to put the app in background (go to the home screen without closing it) to see if you can set a debug point inside the service?

    As for the NotSupportedException, there might be something either by the notification builder that is not supported in the background, or the TaskBuilder(I don't know what use this has) which I don't have in my code.

    The setup towards firebug should be fine, as you are receiving notifications while in the app.

    -Daniel-

    @LerrieG said:
    Here is my code.. it is working when the app is open or background but no notification when app is closed/killed.

    MyBroadcastReceiver.cs
    `using Android.App;
    using Android.Content;
    using Android.Util;
    using Gcm.Client;
    using System.Collections.Generic;
    using WindowsAzure.Messaging;
    using Java.Lang;
    using Android.Media;

    namespace CAMobileApp.Droid
    {
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })] // Allow GCM on boot and when app is closed, but seems like not working
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "[MYPACKAGENAMEHERE]" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "[MYPACKAGENAMEHERE]" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "[MYPACKAGENAMEHERE]" })]

    public class MyBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
    {
        public static string[] SENDER_IDS = new string[] { App.client.SenderId };
        public const string TAG = "MyBroadcastReceiver-GCM";
    }
    
    
    [Service] // Must use the service tag
    public class PushHandlerService : GcmServiceBase
    {
        public static string RegistrationID { get; private set; }
        private NotificationHub Hub { get; set; }
    
        public PushHandlerService() : base(App.client.SenderId)
        {
            Log.Info(MyBroadcastReceiver.TAG, "PushHandlerService() constructor");
        }
    
        protected override void OnRegistered(Context context, string registrationId)
        {
            Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
    
            RegistrationID = registrationId;
    
            Hub = new NotificationHub(App.client.NotiHubPath, App.client.NotiHubConnectionStringListen,
                                        context);
            try
            {
                Hub.UnregisterAll(registrationId);
            }
            catch (Exception ex)
            {
                Log.Error(MyBroadcastReceiver.TAG, ex.Message);
            }
    
            var tags = new List<string>() { };
    
            try
            {
                var hubRegistration = Hub.Register(registrationId, tags.ToArray());
            }
            catch (Exception ex)
            {
                Log.Error(MyBroadcastReceiver.TAG, ex.Message);
            }
        }
    
    
    
        protected override void OnMessage(Context context, Intent intent)
        {
            Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");
            
            var title = "Update";
    
            var msg = new Dictionary<string, string>();
    
            if (intent != null && intent.Extras != null)
            {
                foreach (var key in intent.Extras.KeySet())
                {
                    msg[key] = intent.Extras.Get(key).ToString();
                    System.Console.WriteLine("Key " + intent.Extras.Get(key).ToString());
                }
            }
    
            string Message = msg["message"];
    
            //Store the message
            var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private);
            var edit = prefs.Edit();
            edit.PutString("last_msg", msg.ToString());
            edit.PutString("NotificationMessage", Message);
            edit.PutString("NotificationTitle", title);
            edit.Commit();
            if (Message != "")
            {
                createNotification(title, Message);
            }
    
        }
    
        void createNotification(string title, string desc)
        {
    
            
            #region Perfrences
            var prefs = Xamarin.Forms.Forms.Context.GetSharedPreferences(Xamarin.Forms.Forms.Context.PackageName, FileCreationMode.Private);
            string nmsg = prefs.GetString("NotificationMessage", "");
            string ntitle = prefs.GetString("NotificationTitle", "");
            
            #endregion
    
            var UI_Intent = new Intent(this, typeof(MainActivity));
            UI_Intent.PutExtra("MyData", "MainActivity");
    
            Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
            stackBuilder.AddNextIntent(UI_Intent);
    
            PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
            Notification.Builder builder = new Notification.Builder(this)
            .SetAutoCancel(true) // Remove the notification once the user touches it
            .SetContentTitle(ntitle)
            .SetTicker(ntitle)
            .SetContentIntent(resultPendingIntent)
            .SetContentText(nmsg)
            .SetSmallIcon(Droid.Resource.Drawable.icon)
            .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
    
            Notification notifications = builder.Build();
            NotificationManager notificationsManager = GetSystemService(Context.NotificationService) as NotificationManager;
            notificationsManager.Notify(0, notifications);
    
        }
    

    protected override void OnUnRegistered(Context context, string registrationId)
    {
    Log.Verbose(MyBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId);

        }
    
        protected override bool OnRecoverableError(Context context, string errorId)
        {
            Log.Warn(MyBroadcastReceiver.TAG, "Recoverable Error: " + errorId);
    
            return base.OnRecoverableError(context, errorId);
        }
    
        protected override void OnError(Context context, string errorId)
        {
            Log.Error(MyBroadcastReceiver.TAG, "GCM Error: " + errorId);
        }
    
    }
    

    }`

    MainActivity.cs
    `public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
    public static MainActivity instance;
    const string TAG = "MainActivity";

        protected override void OnCreate(Bundle bundle)
        {
            instance = this;
    
            base.OnCreate(bundle);
    
            global::Xamarin.Forms.Forms.Init(this, bundle);
    
            //get page height
            DeviceScreenSize devicess = FileHelper.GetDeviceSizePx();
    
            string text = Intent.GetStringExtra("MyData") ?? "Data not available";
            if (text == "MainActivity")
            {
                ShowAlert();
                
            }
    
            LoadApplication(new CAMobileApp.App(dbPath, devicess));
    
            RegisterWithGCM();
             
    
        }
    
    
       
        private void RegisterWithGCM()
                {
                    try
                    {
    
                
                        // Check to ensure everything's set up right
                        GcmClient.CheckDevice(this);
                        GcmClient.CheckManifest(this);
    
                        // Register for push notifications
                        Log.Info("MainActivity", "Registering...");
                        GcmClient.Register(this, App.client.SenderId);
                        
    
            }
                    catch (Java.Net.MalformedURLException)
                    {
                        CreateAndShowDialog("There was an error creating the client. Verify the URL.", "Notification Error");
                    }
                    catch (Exception e)
                    {
                        CreateAndShowDialog(e.Message, "Notification Error");
                    }
                }
    
                private void CreateAndShowDialog(String message, String title)
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    
                    builder.SetMessage(message);
                    builder.SetTitle(title);
                    builder.Create().Show();
                }
    
        /// <summary>
        /// Shows the alert for notification.
        /// </summary>
        /// <returns>The notification alert.</returns>
                public void ShowAlert()
                {
                    var prefs = Xamarin.Forms.Forms.Context.GetSharedPreferences(Xamarin.Forms.Forms.Context.PackageName, FileCreationMode.Private);
                    string nmsg = prefs.GetString("NotificationMessage", "");
                    string ntitle = prefs.GetString("NotificationTitle", "");
    
                    AlertDialog.Builder alert = new AlertDialog.Builder(this);
                    alert.SetTitle(ntitle);
                    alert.SetMessage(nmsg);
                    alert.SetPositiveButton("OK", (senderAlert, args) =>
                    {
                        alert.Dispose();
                    });
    
                    RunOnUiThread(() =>
                    {
                        alert.Show();
                    });
                }
    }`
    

    AndroidManifest.xml
    < ?xml version="1.0" encoding="utf-8"? > < manifest ...... ..... > < uses-sdk android:minSdkVersion="15" / > < application android:icon="@drawable/icon" > < / application> < uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" / > < uses-permission android:name="android.permission.ACCESS_WIFI_STATE" / > < uses-permission android:name="android.permission.GET_ACCOUNTS" / > < uses-permission android:name="android.permission.INTERNET" / > < uses-permission android:name="android.permission.WAKE_LOCK" / > < uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" / > < uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" / > < uses-permission android:name="[MYPACKAGENAMEHERE].permission.C2D_MESSAGE" / > < permission android:name="[MYPACKAGENAMEHERE].permission.C2D_MESSAGE" android:protectionLevel="signature" /> < / manifest >

  • LerrieGLerrieG USMember ✭✭

    Hi @JuanVD,
    Does your code work when the app is closed/killed? I am a beginner also. Let me know what notification type you used because that might be the issue on my end. Also, I am using Visual Studio, not sure if its a big difference. Thank you.

  • LerrieGLerrieG USMember ✭✭

    Hi @DanielVartdal ,
    I can do debug when the app is in background and it does let me go inside/point in the service. Not killing the app keep the debug still on. The notification is working when app is open/background but not when killed/closed.

    I put my solution in GitHub, for better view, maybe you guys could try and see if it work with you.
    https://github.com/lerrie/XamarinPCLPushNotification-lg

    Thank you so much.

  • DanielVartdalDanielVartdal USMember ✭✭

    Ah, now I'm with you on what's happening. I'll see if I can share something from my setup when I come home from work, and see if I can get any spare time to test your source code.

    Kind regards,

    Daniel

    @LerrieG said:
    Hi @DanielVartdal ,
    I can do debug when the app is in background and it does let me go inside/point in the service. Not killing the app keep the debug still on. The notification is working when app is open/background but not when killed/closed.

    I put my solution in GitHub, for better view, maybe you guys could try and see if it work with you.
    https://github.com/lerrie/XamarinPCLPushNotification-lg

    Thank you so much.

  • LerrieGLerrieG USMember ✭✭
    edited August 2017

    Also, I just added this code recently while I am researching, found this might help but it doesn't seems like it. Even with or without stackBuilder, notification is still not working when app is closed/killed.

    `Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
    stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
    stackBuilder.AddNextIntent(UI_Intent);

    PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
    var notification = builder.SetContentIntent(resultPendingIntent)`

    without stackBuilder, this is my code.
    var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, uiIntent, 0))

    I also tried this way, but it is also not working also, the "SetLatestEventInfo" says it is deprecated.

    `
    //Create notification
    var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            //Create an intent to show UI
            var uiIntent = new Intent(this, typeof(MainActivity));
    
            //Create the notification
            var notification = new Notification(Resource.Drawable.icon, title);
    
            //Auto-cancel will remove the notification once the user touches it
            notification.Flags = NotificationFlags.AutoCancel;
    
            //Set the notification info
            //we use the pending intent, passing our ui intent over, which will get called
            //when the notification is tapped.
            notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));
    
            //Show the notification
            notificationManager.Notify(1, notification);
            dialogNotify(title, desc);`
    
  • LerrieGLerrieG USMember ✭✭

    Thank you so much please let me know either way. I've been trying/troubleshooting this for few days and giving me headache lol

    @DanielVartdal said:
    Ah, now I'm with you on what's happening. I'll see if I can share something from my setup when I come home from work, and see if I can get any spare time to test your source code.

    Kind regards,

    Daniel

  • LerrieGLerrieG USMember ✭✭

    Hi @DanielVartdal,

    I figured out the issue. My app is working now. Mainly it is because of the reference I created for sender id and notification hub information from PCL Project... App.client.SenderId & etc.

    What I did to solve the issue is to create a Constant class inside the Android Project and store the sender id and notification hub information in that class. I also did some changes in createNotification function. I pass the context field from OnMessage and use to create intent & etc.

    Best Regards,
    Lerrie

  • LerrieGLerrieG USMember ✭✭

    Hi Daniel,
    Yes, it is working when the app is running or background and I am using Gcm.Client. But when the app is closed/killed, no notification and I receive error message that the app has stopped working.

    If of any help, this is the error message i receive when i deploy in Google Play:

    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    ... 2 more
    Caused by: android.runtime.JavaProxyThrowable: System.NotSupportedException: Could not activate JNI Handle 0xeed00025 (key_handle 0x420b8ff8) of Java type 'md5feb66ad60a272ca503c0cef49b342a37/MyBroadcastReceiver' as managed type 'CAMobileApp.Droid.MyBroadcastReceiver'. ---> System.TypeInitializationException: The type initializer for 'CAMobileApp.Droid.MyBroadcastReceiver' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object
    at CAMobileApp.Droid.MyBroadcastReceiver..cctor () [0x00000] in <48815d327f844c3dbe0a1cdf4e3a8b35>:0
    --- End of inner exception stack trace ---
    at (wrapper dynamic-method) System.Object:bd4b06dc-298c-4e1c-85b5-1a68bcdc6de1 (intptr,object[])
    at Java.Interop.TypeManager.n_Activate (System.IntPtr jnienv, System.IntPtr jclass, System.IntPtr typename_ptr, System.IntPtr signature_ptr, System.IntPtr jobject, System.IntPtr parameters_ptr) [0x000de] in <10142b15afc84717ae12134b2795429d>:0
    --- End of inner exception stack trace ---
    at Java.Interop.TypeManager.n_Activate (System.IntPtr jnienv, System.IntPtr jclass, System.IntPtr typename_ptr, System.IntPtr signature_ptr, System.IntPtr jobject, System.IntPtr parameters_ptr) [0x00167] in <10142b15afc84717ae12134b2795429d>:0
    at (wrapper dynamic-method) System.Object:d54b59fc-59ab-4d84-b9a1-d0053239977b (intptr,intptr,intptr,intptr,intptr,intptr)
    at mono.android.TypeManager.n_activate(Native Method)
    at mono.android.TypeManager.Activate(TypeManager.java:7)
    at md5feb66ad60a272ca503c0cef49b342a37.MyBroadcastReceiver.(MyBroadcastReceiver.java:22)
    at java.lang.Class.newInstanceImpl(Native Method)
    at java.lang.Class.newInstance(Class.java:1208)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2542)
    at android.app.ActivityThread.access$1800(ActivityThread.java:169)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5487)
    ... 5 more

  • LerrieGLerrieG USMember ✭✭

    @DanielVartdal said:
    Hi Lerrie,

    you have got it working when the app is running? Are you able to share some of your code for the GCM?

    -Daniel-

    Hi Daniel,
    Yes, it is working when the app is running or background and I am using Gcm.Client. But when the app is closed/killed, no notification and I receive error message that the app has stopped working.

    If of any help, this is the error message i receive when i deploy in Google Play:

    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    ... 2 more
    Caused by: android.runtime.JavaProxyThrowable: System.NotSupportedException: Could not activate JNI Handle 0xeed00025 (key_handle 0x420b8ff8) of Java type 'md5feb66ad60a272ca503c0cef49b342a37/MyBroadcastReceiver' as managed type 'CAMobileApp.Droid.MyBroadcastReceiver'. ---> System.TypeInitializationException: The type initializer for 'CAMobileApp.Droid.MyBroadcastReceiver' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object
    at CAMobileApp.Droid.MyBroadcastReceiver..cctor () [0x00000] in <48815d327f844c3dbe0a1cdf4e3a8b35>:0
    --- End of inner exception stack trace ---
    at (wrapper dynamic-method) System.Object:bd4b06dc-298c-4e1c-85b5-1a68bcdc6de1 (intptr,object[])
    at Java.Interop.TypeManager.n_Activate (System.IntPtr jnienv, System.IntPtr jclass, System.IntPtr typename_ptr, System.IntPtr signature_ptr, System.IntPtr jobject, System.IntPtr parameters_ptr) [0x000de] in <10142b15afc84717ae12134b2795429d>:0
    --- End of inner exception stack trace ---

  • DanielVartdalDanielVartdal USMember ✭✭

    Hi again @LerrieG

    are you using MvvmCross?

    The error: System.NotSupportedException: Could not activate JNI Handle 0xeed00025 error seems to be related to MvvmCross based on a google search: https://www.google.no/search?q=System.NotSupportedException:+Could+not+activate+JNI+Handle+0xeed00025&amp;oq=System.NotSupportedException:+Could+not+activate+JNI+Handle+0xeed00025&amp;aqs=chrome..69i57j69i59.1550j0j7&amp;sourceid=chrome&amp;ie=UTF-8

    My guess is that there are some converting error between Xamarin Forms / Native Android broadcastreceivers. But I haven't worked with Xamarin Forms, so I can't really say..

  • pythpyth Member ✭✭

    I had the same problem as the OP.
    The problem was that I did not placed the tags into the manifest at the right place.
    I had it placed inside the tag but not inside the tag.

  • meghatiwarimeghatiwari USMember ✭✭
    edited August 2018

    hello!!! To All

    I am working on android native app, In which I have completed notification send and recived using Google Firebase when my screen is on but, In this I need a help when mobile screen is off my notification is not working.

    Anybody have any idea?

  • nick5454nick5454 USUniversity ✭✭✭

    Use this as an example Try Xamarin

Sign In or Register to comment.