Firebase Cloud Messaging

KimJensenKimJensen USMember ✭✭

Have any one got this example to work: "Remote Notifications with Firebase Cloud Messaging" found here: Android / Application Fundamentals / Notifications. I get the token, but when I use it I do not get any notification and the Firebase Console do not have any registered phones. If I add this to the code: "Log.Debug(TAG, "google app id: " + Resource.String.google_app_id);" I should see if the google-services.json was parsed correctly, i get a number but not the mobilesdk_app_id value recorded in google-services.json.

Posts

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Try this Code:

    //App AndroidManifest

    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:enabled="true" 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>
    

    //Get Instance ID
    Task.Run(() =>
    {
    var instanceid = FirebaseInstanceId.Instance;
    instanceid.DeleteInstanceId();
    Log.Debug("TAG", "{0} {1}", instanceid.Token, instanceid.GetToken(context.GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));

            });
    

    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]

    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) 
        { 
    

    //Get Token
    }
    }

    //FirebaseMessagingService

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]

    class MyFireMessagingService : FirebaseMessagingService
    {
        public override void OnMessageReceived(RemoteMessage message)
        {
            base.OnMessageReceived(message);
            SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);
        }
        public void SendNotificatios(string body,string Header)
        {
    
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
             builder.SetSmallIcon(Resource.Drawable.ic_luncher);
            var intent = new Intent(this, typeof(Go_HomePage));
            intent.AddFlags(ActivityFlags.ClearTop); 
            PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
            builder.SetContentIntent(pendingIntent);
            builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_luncher));
            builder.SetContentTitle(Header);
            builder.SetContentText(body);
            NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.Notify(1, builder.Build());
    
        }
    }
    

    //Server Side Push The Notification

          string SERVER_API_KEY = "API KEY VALUE";
            var SENDER_ID = "SENDER ID";
            var value = message;
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            //tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    
            tRequest.ContentType = "application/json";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
    
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); 
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = "TEXT",
                    title = "TEXT",
                    icon = "TEXT"
                }
            };
    
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.ContentLength = byteArray.Length;
    
            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse tResponse = tRequest.GetResponse();
            dataStream = tResponse.GetResponseStream();
            StreamReader tReader = new StreamReader(dataStream);
    
            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close();
    
  • KimJensenKimJensen USMember ✭✭

    Thanks.
    I'm not sure were I will place the:
    //Get Instance ID
    Task.Run(() =>

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @KimJensen No need below code ..we need only Device ID

    Task.Run(() =>
    {
    var instanceid = FirebaseInstanceId.Instance;
    instanceid.DeleteInstanceId();
    Log.Debug("TAG", "{0} {1}", instanceid.Token, instanceid.GetToken(context.GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));

        });
    
  • KimJensenKimJensen USMember ✭✭

    I get this error when this line is executed: var instanceid = FirebaseInstanceId.Instance;

    Unhandled Exception:
    Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.xamarin.fcmexample. Make sure to call FirebaseApp.initializeApp(Context) first.

  • KimJensenKimJensen USMember ✭✭

    I did get it to work on a real device. I only get notification if the app is running. If I send a message when the app is not running the message never get to the device.

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @KimJensen Add AndroidManifest below code

    <uses-permission android:name="android.permission.WAKE_LOCK" />

  • AlbertKAlbertK MYMember ✭✭✭✭

    @AnbuVijay27 Do you know of a way to get a new token when I redeploy a release build?. When I rebuild and redeploy a release version to the physical device the token will still be the same one as the initial install/deploy.

    Somehow Android will invalidate the token to the Firebase server (google) when a redeploy is done but the Firebase instance will still happily return the previous token which is not invalid for use to send message to the device.

    Is there a way to know that the current app is a redeployed one? Thank you.

  • KimJensenKimJensen USMember ✭✭

    Thanks, again.

  • AlbertKAlbertK MYMember ✭✭✭✭

    Hi,
    May I know what I am supposed to do with the debug keystore? Thanks.

  • KimJensenKimJensen USMember ✭✭

    I was going crazy because it worked and then it didn't work. In the end I found It will not work without it's started from the device first.

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @AlbertK i given the link also have both debug and release key creation steps.

  • AlbertKAlbertK MYMember ✭✭✭✭

    @AnbuVijay27 said:
    Hi @AlbertK i given the link also have both debug and release key creation steps.

    Hi @AnbuVijay27 ,

    I have no problem with the debug and release keystore.

    My issue is with the Firebase Instance Token getting invalidated (as indicated by Firebase portal) when I recompile and redeploy the same app on the same Physical Device. Hope to be able to get around this problem. Thanks.

    For example,

    1) The Token I get on the fresh install of my app on a Physical Device (release mode).

    fUcbvoh_928:APA91bFWqp8tbLRknF7dKxADIROOfhzG18fv2RHyLFKdDy9XMAGYhIYiurskzHIyT_vQ4zX6CaWC1WvdywUXF0zQgZIUNpjpplM7a26dwlfIThhpqlTCRjWjT3hYoEYnYMwFlxWdxTiz

    2) Test send notification with Firebase Messaging https://console.firebase.google.com/
    I get a notification on my App

    3) Recompile my app and redeploy to the same Physical Device and the Token I get is as below. Identical to the initial Token (release mode).

    fUcbvoh_928:APA91bFWqp8tbLRknF7dKxADIROOfhzG18fv2RHyLFKdDy9XMAGYhIYiurskzHIyT_vQ4zX6CaWC1WvdywUXF0zQgZIUNpjpplM7a26dwlfIThhpqlTCRjWjT3hYoEYnYMwFlxWdxTiz

    4) 2) Test send notification with Firebase Messaging https://console.firebase.google.com/
    Firebase return a error "Unregistered Registration Token"

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @AlbertK every recompile time token will be refresh&changed,so only u get this error "Firebase return a error "Unregistered Registration Token" " , so i try push the messages with Device Id

  • AlbertKAlbertK MYMember ✭✭✭✭

    @AnbuVijay27 said:
    Hi @AlbertK every recompile time token will be refresh&changed,so only u get this error "Firebase return a error "Unregistered Registration Token" " , so i try push the messages with Device Id

    Thanks, I still feel that the Firebase Messaging module should invalidate token and initialize a new token (on the App) when a recompile is detected otherwise testing the app would be a pain.

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    Hi @AlbertK Cool :smile: Use Device ID its better for push the messages

  • AlbertKAlbertK MYMember ✭✭✭✭

    @AnbuVijay27 said:
    Hi @AlbertK Cool :smile: Use Device ID its better for push the messages

    May I know which API to use ? Thanks.

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    @AlbertK you can create separate API for message push

    try to use below sample code

    //Server Side Push The Notification
    
          string SERVER_API_KEY = "API KEY VALUE";
            var SENDER_ID = "SENDER ID";
            var value = message;
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            //tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    
            tRequest.ContentType = "application/json";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
    
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); 
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = "TEXT",
                    title = "TEXT",
                    icon = "TEXT"
                }
            };
    
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.ContentLength = byteArray.Length;
    
            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse tResponse = tRequest.GetResponse();
            dataStream = tResponse.GetResponseStream();
            StreamReader tReader = new StreamReader(dataStream);
    
            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close(); 
    
  • AlbertKAlbertK MYMember ✭✭✭✭

    @AnbuVijay27 said:
    @AlbertK you can create separate API for message push

    try to use below sample code

    //Server Side Push The Notification
    
          string SERVER_API_KEY = "API KEY VALUE";
            var SENDER_ID = "SENDER ID";
            var value = message;
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            //tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    
            tRequest.ContentType = "application/json";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
    
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); 
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = "TEXT",
                    title = "TEXT",
                    icon = "TEXT"
                }
            };
    
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.ContentLength = byteArray.Length;
    
            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse tResponse = tRequest.GetResponse();
            dataStream = tResponse.GetResponseStream();
            StreamReader tReader = new StreamReader(dataStream);
    
            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close(); 
    

    The device Id that you have mentioned here is the FCM registration token. That is the problem that i am facing know where a recompiled app will give the same FCM token/device id even though the token is now invalidated by Firebase..

  • AnbuMani27AnbuMani27 USMember ✭✭✭

    @AlbertK Here we are not mention any token ,only we used API KEY VALUE and SENDER ID, no need token for this API

  • AlbertKAlbertK MYMember ✭✭✭✭
    edited April 2017

    SENDER_ID is your Firebase Cloud Messaging ID ("owner" of the Firebase messaging server)
    where as the deviceid is the FCM Registration Token and without this you are not going to be able to target anyone.

    var data = new
    {
    to = deviceId,
    notification = new
    {
    body = "TEXT",
    title = "TEXT",
    icon = "TEXT"
    }
    };

  • BoVisfeldtBoVisfeldt DKMember ✭✭

    @AlbertK did you figure out a way to get this to work? I am facing the same problem.

  • KimJensenKimJensen USMember ✭✭

    @BoVisfeldt The only way I got it to work was to run it on a device it would not work in debugging mode.

  • msmanju1965msmanju1965 Member ✭✭

    @AnbuMani27 said:
    Try this Code:

    //App AndroidManifest








    //Get Instance ID
    Task.Run(() =>
    {
    var instanceid = FirebaseInstanceId.Instance;
    instanceid.DeleteInstanceId();
    Log.Debug("TAG", "{0} {1}", instanceid.Token, instanceid.GetToken(context.GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));

    });


    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]


    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)
    {
    //Get Token
    }
    }

    //FirebaseMessagingService

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]

    class MyFireMessagingService : FirebaseMessagingService
    {
    public override void OnMessageReceived(RemoteMessage message)
    {
    base.OnMessageReceived(message);
    SendNotificatios(message.GetNotification().Body, message.GetNotification().Title);
    }
    public void SendNotificatios(string body,string Header)
    {

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.SetSmallIcon(Resource.Drawable.ic_luncher);
    var intent = new Intent(this, typeof(Go_HomePage));
    intent.AddFlags(ActivityFlags.ClearTop);
    PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
    builder.SetContentIntent(pendingIntent);
    builder.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_luncher));
    builder.SetContentTitle(Header);
    builder.SetContentText(body);
    NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.Notify(1, builder.Build());

        }
    }
    

    //Server Side Push The Notification

          string SERVER_API_KEY = "API KEY VALUE";
            var SENDER_ID = "SENDER ID";
            var value = message;
            WebRequest tRequest;
            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            //tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
    
            tRequest.ContentType = "application/json";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
    
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); 
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = "TEXT",
                    title = "TEXT",
                    icon = "TEXT"
                }
            };
    
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            tRequest.ContentLength = byteArray.Length;
    
            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse tResponse = tRequest.GetResponse();
            dataStream = tResponse.GetResponseStream();
            StreamReader tReader = new StreamReader(dataStream);
    
            String sResponseFromServer = tReader.ReadToEnd();
            tReader.Close();
            dataStream.Close();
            tResponse.Close();
    

    How can i get Token (device Id) after login to the app?

  • msmanju1965msmanju1965 Member ✭✭

    Hi,
    var FCMTockenValue = Application.Current.Properties["Fcmtocken"].ToString();

    when we try to get fcmtoken am getting error like bellow

    "The given key 'FcmTocken' was not present in the dictionary"

  • msmanju1965msmanju1965 Member ✭✭

    Hi,

    var data = new
    {
    to = deviceId,
    notification = new
    {
    body = "TEXT",
    title = "TEXT",
    icon = "TEXT"
    }
    };

    i want to send all users how can i do? (to="?")

    thanks in advance.

Sign In or Register to comment.