Forum Xamarin.Android

Firebase configuration

2

Posts

  • JonathanDickJonathanDick CAXamarin Team, Developer Group Leader Xamurai

    Hey folks, sorry for the delay here, was just alerted to this post.

    Basically, you are all on the right track. Google has a gradle plugin to handle the google-services.json file and essentially put the correct values from that json file into the correct resource string key/value pairs.

    You can certainly do this manually, in fact, Google has documented the values and where they go: https://developers.google.com/android/guides/google-services-plugin

    As some of you found, we do have a custom build task which is supposed to take care of doing this for you. This build task gets referenced via the targets file in the Xamarin.GoogleServices.Basement nuget package when you install it. Once you've added your nuget packages, you need to add your google-services.json file to your project, and finally set the build action of that file to GoogleServicesJson. This should cause the correct values to go to the correct place.

    As a bonus, this also means if you need to get fancy with multiple google-services.json files (let's say for test and production builds), you could easily configure your .csproj file to use the correct one for the correct conditions.

    Finally, there's a new prerelease version of Google Play Services and Firebase due out very very shortly (maybe tonight even) which will be v32.4.0-beta1. I'd suggest updating to it as Google's fixed some bugs in firebase along the way.

    If you have issues with this, please feel free to open github issues on the source code repository. I don't always check the forums to see posts about GPS/Firebase.

    Thanks :)

  • mrmiagi0101mrmiagi0101 DEMember ✭✭
    edited September 2016

    Hallo,
    I created a new Xamarin.Forms Project (2.3.1.114). Then installed Xamarin.Firebase.Messaging Nuget (32.4.0-beta2) in the Droid Project. I made everything like in the quickstart project.

    Added this in the mainactivity:

    Task.Run(() => { var instanceID = FirebaseInstanceId.Instance; instanceID.DeleteInstanceId(); var iid1 = instanceID.Token; var iid2 = instanceID.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope); var test = iid2; });

    My Services:
    [Service()] [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })] public class SMFirebaseIdService: FirebaseInstanceIdService { public override void OnTokenRefresh() { var refreshedToken = FirebaseInstanceId.Instance.Token; SendRegistrationToServer(refreshedToken); } private void SendRegistrationToServer(string token) { var test = token; } [Service] [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] public class SMFirebaseMessagingService: FirebaseMessagingService { public override void OnMessageReceived(RemoteMessage message) { // TODO(developer): Handle FCM messages here. // If the application is in the foreground handle both data and notification messages here. // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. var test = message; this.SendNotificationToUser("ERhalten"); }

    I get a token, but my services are never called. E.g. OnTokenRefresh() or OnMessageReceived() (Send massage over Firebase Console to token)

    Any suggestions?

  • sudhir.9350sudhir.9350 INUniversity ✭✭

    I do have the same problem. i installed "Xamarin Firebase - Messaging 32.4.0-beta2" in my droid project. I get the token, but my services are never called. I want to use it for Push notification.

    Here is my MainActivity:

    protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
    
            global::Xamarin.Forms.Forms.Init (this, bundle);
    
            var options = new FirebaseOptions.Builder()
                .SetApplicationId(ApplicationId)
                .SetApiKey(ApiKey)
                //.SetDatabaseUrl("Firebase-Database-Url")
                .SetGcmSenderId(GcmSenderId)
                .Build();
    
            var firebaseApp = FirebaseApp.InitializeApp(this, options);
            // Generate token in background thread
            Task.Run (() => {
                var instanceID = FirebaseInstanceId.Instance;
                instanceID.DeleteInstanceId ();
                var iid1 = instanceID.Token;
                var iid2 = instanceID.GetToken (GcmSenderId, Firebase.Messaging.FirebaseMessaging.InstanceIdScope);
                Console.WriteLine( "Iid1: {0}, iid2: {1}", iid1, iid2);
            });
    
            LoadApplication (new App ());
    
        }
    

    and here is the services:

    [Service]
    [IntentFilter (new [] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
        const string TAG = "MyFirebaseIIDService";
    
        public override void OnTokenRefresh ()
        {
            // Get updated InstanceID token.
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Android.Util.Log.Debug (TAG, "Refreshed token: " + refreshedToken);
    
            // TODO: Implement this method to send any registration to your app's servers.
            SendRegistrationToServer (refreshedToken);
        }
        // [END refresh_token]
    
        void SendRegistrationToServer (string token)
        {
            // Add custom implementation, as needed.
        }
    }
    
    [Service]
    [IntentFilter (new [] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
        const string TAG = "MyFirebaseMsgService";
    
        public override void OnMessageReceived (RemoteMessage message)
        {
            Android.Util.Log.Debug (TAG, "From: " + message.From);
            Android.Util.Log.Debug (TAG, "Notification Message Body: " + message.GetNotification ().Body);
        }
    
        void SendNotification (string messageBody)
        {
            var intent = new Intent (this, typeof (MainActivity));
            intent.AddFlags (ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity (this, 0 /* Request code */, intent, PendingIntentFlags.OneShot);
    
            var defaultSoundUri = RingtoneManager.GetDefaultUri (RingtoneType.Notification);
            var notificationBuilder = new NotificationCompat.Builder (this)
                .SetContentTitle ("FCM Message")
                .SetContentText (messageBody)
                .SetAutoCancel (true)
                .SetSound (defaultSoundUri)
                .SetContentIntent (pendingIntent);
    
            var notificationManager = NotificationManager.FromContext (this);
    
            notificationManager.Notify (0, notificationBuilder.Build ());
        }
    }
    

    In one of the issue in that github (https://github.com/xamarin/GooglePlayServicesComponents/issues/14) Anth0ny229 suggested :
    "I was finally able to get it working by opening the Firebase-Iid project and updating the nuget package for the Xamarin.Android.Support.v4. "

    So i tried to upgrade to Xamarin.Android.Support.v4 in my sample, but it gives me following error:

    Updating Xamarin.Android.Support.v4
    Looking for updates for 'Xamarin.Android.Support.v4'...
    Updating 'Xamarin.Android.Support.v4' from version '23.3.0' to '23.4.0.1' in project 'firebasetest.Droid'.
    Updating 'Xamarin.Android.Support.v4 23.3.0' to 'Xamarin.Android.Support.v4 23.4.0.1' failed. Unable to find versions of 'Xamarin.Android.Support.Animated.Vector.Drawable, Xamarin.Android.Support.v7.AppCompat, Xamarin.Android.Support.v7.RecyclerView, Xamarin.Android.Support.Design, Xamarin.Android.Support.v7.MediaRouter, Xamarin.Forms' that are compatible with 'Xamarin.Android.Support.v4 23.4.0.1
    

    So the android support library is not compatible with Xamarin.forms.

    Any idea/suggestions ?
    Thanks.

  • MikePetersMikePeters USMember ✭✭

    I have not had any success with this either.

    When I try to initialize:
    FirebaseApp app = FirebaseApp.InitializeApp(this, options);
    I get this error:
    "FirebaseApp name [DEFAULT] already exists!"

    If I comment out that line, I can get a token, however messsaging doesn't work.

    If I check the current app, like this:
    var app = FirebaseInstanceId.Instance;
    of course it doesn't have the correct options (app id, api key, gmc sender) because I didn't initialize it above.

    So, how is the app getting initialized in the first place if I commented out "FirebaseApp.InitializeApp"?
    And how could I initialize it with my own options?

    Thanks!

  • MikePetersMikePeters USMember ✭✭
    edited September 2016

    @MikePeters said:
    I have not had any success with this either.

    When I try to initialize:
    FirebaseApp app = FirebaseApp.InitializeApp(this, options);
    I get this error:
    "FirebaseApp name [DEFAULT] already exists!"

    If I comment out that line, I can get a token, however messsaging doesn't work.

    If I check the current app, like this:
    var app = FirebaseInstanceId.Instance;
    of course it doesn't have the correct options (app id, api key, gmc sender) because I didn't initialize it above.

    So, how is the app getting initialized in the first place if I commented out "FirebaseApp.InitializeApp"?
    And how could I initialize it with my own options?

    Thanks!

    Figured part of it out. Somehow I had a leftover resource:
    <string name="google_app_id">72222222222</string>

    Once I deleted it, the Default app isn't being created anymore and I can initialize it with my options.

    However, OnMessageReceived still isn't being hit. And when I try this:

    FirebaseMessaging.Instance.SubscribeToTopic("test");

    I don't see the topic listed in the Firebase console.

    I've spent hours trying to figure Messaging out. If anyone has any advice, I would really appreciate it!

    Thanks!

  • MikePetersMikePeters USMember ✭✭

    @JonathanDick said:
    Hey folks, sorry for the delay here, was just alerted to this post.

    Basically, you are all on the right track. Google has a gradle plugin to handle the google-services.json file and essentially put the correct values from that json file into the correct resource string key/value pairs.

    You can certainly do this manually, in fact, Google has documented the values and where they go: https://developers.google.com/android/guides/google-services-plugin

    As some of you found, we do have a custom build task which is supposed to take care of doing this for you. This build task gets referenced via the targets file in the Xamarin.GoogleServices.Basement nuget package when you install it. Once you've added your nuget packages, you need to add your google-services.json file to your project, and finally set the build action of that file to GoogleServicesJson. This should cause the correct values to go to the correct place.

    As a bonus, this also means if you need to get fancy with multiple google-services.json files (let's say for test and production builds), you could easily configure your .csproj file to use the correct one for the correct conditions.

    Finally, there's a new prerelease version of Google Play Services and Firebase due out very very shortly (maybe tonight even) which will be v32.4.0-beta1. I'd suggest updating to it as Google's fixed some bugs in firebase along the way.

    If you have issues with this, please feel free to open github issues on the source code repository. I don't always check the forums to see posts about GPS/Firebase.

    Thanks :)

    Hi Jonathan,
    I am testing Firebase Messaging in my Xamarin app.

    I am initializing FirebaseApp with my options, like this:

                    var options = new FirebaseOptions.Builder()
                        .SetApplicationId(firebase_app_id)
                        .SetApiKey(firebase_api_key)
                        .SetGcmSenderId(firebase_gcm_sender_id)
                        .Build();
    
                    FirebaseApp app = FirebaseApp.InitializeApp(this, options);
    

    Do I still need to add the google-services.json file to my project?

    I don't think I do, but the messaging isn't working (OnMessageReceived never gets hit) so I'm trying to figure out what is wrong and I just wanted to clarify that I do not need to add this file.

    Thanks!

  • mrmiagi0101mrmiagi0101 DEMember ✭✭

    If you get a token, init works. But OnMessageReceived is never called. So I switched to GCM Listener System, because with this also FirebaseMessaging is working and my apps get the message from Firebase Server.

  • JGoldbergerJGoldberger USMember, Forum Administrator, Xamarin Team, University Xamurai

    As noted by @JonathanDick , issues with the FCM component should be filed on github:

    https://github.com/xamarin/GooglePlayServicesComponents/issues

  • JGoldbergerJGoldberger USMember, Forum Administrator, Xamarin Team, University Xamurai
  • nshpnshp USUniversity ✭✭

    When we get any progress with Firebase Messaging dlls ? Spent few hours today but get no luck. Maybe any of you guys have git with working project ?

  • MikePetersMikePeters USMember ✭✭

    Figured part of it out. Somehow I had a leftover resource:
    <string name="google_app_id">72222222222</string>

    Once I deleted it, the Default app isn't being created anymore and I can initialize it with my options.

    However, OnMessageReceived still isn't being hit. And when I try this:

    FirebaseMessaging.Instance.SubscribeToTopic("test");

    I don't see the topic listed in the Firebase console.

    I've spent hours trying to figure Messaging out. If anyone has any advice, I would really appreciate it!

    Thanks!

    So when I took out the string resource "google_app_id", I was able to initialize my FirebaseApp successfully. However, eventually I started getting this error, (which I assume is why I had it there in the first place):

    "Missing google app id value from from string resources with name google_app_id"

    But then when I put the string resource back, then my FirebaseApp gets initialized automatically and I am not able to inject my FirebaseOptions.

    I know Firebase is beta, but shouldn't the very basics work? Or am I missing something here?

  • MikePetersMikePeters USMember ✭✭

    So when I took out the string resource "google_app_id", I was able to initialize my FirebaseApp successfully. However, eventually I started getting this error, (which I assume is why I had it there in the first place):

    "Missing google app id value from from string resources with name google_app_id"

    But then when I put the string resource back, then my FirebaseApp gets initialized automatically and I am not able to inject my FirebaseOptions.

    I know Firebase is beta, but shouldn't the very basics work? Or am I missing something here?

    As far as I can tell, this is how it is working for me. When I include the "google_app-id" string resource, Firebase gets initialized automatically with the google-services.json file that I added to my project (with build action GoogleServicesJson).

    When I exclude the "google_app_id" string resource, I need to initialize Firebase manually.

    However, when I call this:
    FirebaseAuth auth = FirebaseAuth.GetInstance(app);

    I get this error:
    Java.Lang.NoClassDefFoundError: com.google.android.gms.internal.zzafi$zza

    I was under the impression that the Xamarin.Firebase packages included everything I need. Why am I missing "com.google.android.gms"?

    Thanks

  • RyanGRyanG USMember

    I've only been able to get this fully working in the FirebaseMessagingQuickstart sample project following @AnthonyClark 's instructions (though I used the latest github branch - 9.4).

    @AnthonyClark said:
    @ArmandCharbonnier I finally got it working!!!

    Using the latest Github branch and following the build instructions.
    After building, I opened up the solution and updated the reference for the Nuget Package Xamarin.Android.Support.v4 in the Firebase-Iid Project.
    Once done I rebuilt
    And then I used the FirebaseMessagingQuickstart sample and modified the google-services.json file and changed the package name in the properties to match mine in the Firebase console test project.
    After that I uncommented the Task.Run region in the MainActivity.cs

            Task.Run (() => {
                var instanceID = FirebaseInstanceId.Instance;
                instanceID.DeleteInstanceId ();
                var iid1 = instanceID.Token;
                var iid2 = instanceID.GetToken (GetString (Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope);
                Android.Util.Log.Debug (TAG, "Iid1: {0}, iid2: {1}", iid1, iid2);
            });
    

    After building and running it, it finally hit my breakpoints for both Instance ID OnTokenRefresh and the OnMessageReceived.

    I say fully because when I created a new solution and referenced the necessary firebase dll's that are created when you build GooglePlayServices, I was actually able to receive messages sent from the console. However, OnTokenRefresh() is never called which I find odd because I thought that would have to be called if I'm receiving messages.

    I'm also curious if others in this thread that are having issues are just trying to use the nuget packages? I ask because I have not been able to get anything to work when using the firebase nuget packages.

  • MikePetersMikePeters USMember ✭✭

    @RyanG said:
    I've only been able to get this fully working in the FirebaseMessagingQuickstart sample project following @AnthonyClark 's instructions (though I used the latest github branch - 9.4).

    @AnthonyClark said:
    @ArmandCharbonnier I finally got it working!!!

    Using the latest Github branch and following the build instructions.
    After building, I opened up the solution and updated the reference for the Nuget Package Xamarin.Android.Support.v4 in the Firebase-Iid Project.
    Once done I rebuilt
    And then I used the FirebaseMessagingQuickstart sample and modified the google-services.json file and changed the package name in the properties to match mine in the Firebase console test project.
    After that I uncommented the Task.Run region in the MainActivity.cs

            Task.Run (() => {
                var instanceID = FirebaseInstanceId.Instance;
                instanceID.DeleteInstanceId ();
                var iid1 = instanceID.Token;
                var iid2 = instanceID.GetToken (GetString (Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope);
                Android.Util.Log.Debug (TAG, "Iid1: {0}, iid2: {1}", iid1, iid2);
            });
    

    After building and running it, it finally hit my breakpoints for both Instance ID OnTokenRefresh and the OnMessageReceived.

    I say fully because when I created a new solution and referenced the necessary firebase dll's that are created when you build GooglePlayServices, I was actually able to receive messages sent from the console. However, OnTokenRefresh() is never called which I find odd because I thought that would have to be called if I'm receiving messages.

    I'm also curious if others in this thread that are having issues are just trying to use the nuget packages? I ask because I have not been able to get anything to work when using the firebase nuget packages.

    I downloaded a sample called FirebaseTest and it seems like it works for me. The difference I notice is it uses 30.0.2-alpha1, while my project that is giving me errors is using 32.4.0-beta2

  • ApiratPuttaraksaApiratPuttaraksa USMember
    edited September 2016

    Hi,
    After i followed all of your guide i have this result
    FirebaseMessagingServiceTag( 8151): Iid1:
    FirebaseMessagingServiceTag( 8151): Iid2: eHs1mIgsJYQ:APA91bFr8pqthwhbum...

    with the following code

    string iid2; Task.Run(() => { var instanceId = FirebaseInstanceId.Instance; instanceId.DeleteInstanceId(); var iid1 = FirebaseInstanceId.Instance.Token; iid2 = instanceId.GetToken("myAppId", Firebase.Messaging.FirebaseMessaging.InstanceIdScope); Log.Debug("FirebaseMessagingServiceTag", "Iid1: {0}", iid1); Log.Debug("FirebaseMessagingServiceTag", "Iid2: {0}", iid2); });

    Am i right to get only iid2. Also i can't get any message from my firebase console.

  • @ApiratPuttaraksa said:
    Hi,
    After i followed all of your guide i have this result
    FirebaseMessagingServiceTag( 8151): Iid1:
    FirebaseMessagingServiceTag( 8151): Iid2: eHs1mIgsJYQ:APA91bFr8pqthwhbum...

    with the following code

    string iid2; Task.Run(() => { var instanceId = FirebaseInstanceId.Instance; instanceId.DeleteInstanceId(); var iid1 = FirebaseInstanceId.Instance.Token; iid2 = instanceId.GetToken("myAppId", Firebase.Messaging.FirebaseMessaging.InstanceIdScope); Log.Debug("FirebaseMessagingServiceTag", "Iid1: {0}", iid1); Log.Debug("FirebaseMessagingServiceTag", "Iid2: {0}", iid2); });

    Am i right to get only iid2. Also i can't get any message from my firebase console.

    @ApiratPuttaraksa said:
    Hi,
    After i followed all of your guide i have this result
    FirebaseMessagingServiceTag( 8151): Iid1:
    FirebaseMessagingServiceTag( 8151): Iid2: eHs1mIgsJYQ:APA91bFr8pqthwhbum...

    with the following code

    string iid2; Task.Run(() => { var instanceId = FirebaseInstanceId.Instance; instanceId.DeleteInstanceId(); var iid1 = FirebaseInstanceId.Instance.Token; iid2 = instanceId.GetToken("myAppId", Firebase.Messaging.FirebaseMessaging.InstanceIdScope); Log.Debug("FirebaseMessagingServiceTag", "Iid1: {0}", iid1); Log.Debug("FirebaseMessagingServiceTag", "Iid2: {0}", iid2); });

    Am i right to get only iid2. Also i can't get any message from my firebase console.

    And i already set SHA-1 and package name to my firebase console but still have no luck OnMessageReceived

  • MikePetersMikePeters USMember ✭✭

    Whoever has gotten OnMessageReceived to work, can you confirm that you are using:
    Xamarin Firebase version 32.4.0-beta2
    I've tried everything and can't get it to work.

  • brianduccabrianducca ARMember ✭✭

    someone has successfully done it? i can't get it to work, please if you could, bring the clean code!
    Thanks!

  • JonathanDickJonathanDick CAXamarin Team, Developer Group Leader Xamurai

    I've updated the github issue with the fix: https://github.com/xamarin/GooglePlayServicesComponents/issues/20

  • MikePetersMikePeters USMember ✭✭

    Xamarin Firebase version 32.4.0-beta2> @JonathanDick said:

    I've updated the github issue with the fix: https://github.com/xamarin/GooglePlayServicesComponents/issues/20

    Great. Thanks. I'll test later tonight.

  • MikePetersMikePeters USMember ✭✭

    @JonathanDick said:
    I've updated the github issue with the fix: https://github.com/xamarin/GooglePlayServicesComponents/issues/20

    OnMessageReceived and OnTokenRefresh are now being hit.
    Thanks so much!!!

    One question about the Firebase authentication. Would you recommend using this in conjunction with Xamarin.Auth?
    So, a user logs in using Firebase, and a FirebaseUser is returned. Then use the Firebase UserID to query my server to get user profile, and then put that info into Xamarin Auth account store? Does this sound about right, or not?

    Thanks again!

  • brianduccabrianducca ARMember ✭✭

    @MikePeters said:

    @JonathanDick said:
    I've updated the github issue with the fix: https://github.com/xamarin/GooglePlayServicesComponents/issues/20

    OnMessageReceived and OnTokenRefresh are now being hit.
    Thanks so much!!!

    One question about the Firebase authentication. Would you recommend using this in conjunction with Xamarin.Auth?
    So, a user logs in using Firebase, and a FirebaseUser is returned. Then use the Firebase UserID to query my server to get user profile, and then put that info into Xamarin Auth account store? Does this sound about right, or not?

    Thanks again!

    @MikePeters i've tested and it is not working for me, i've done copy& paste from the code you added, the only difference relies in MainActivity when setting options in firebase, i've manually added the appid, apikey & gcmsender id.

                var options = new FirebaseOptions.Builder()
                            .SetApplicationId("")
                            .SetApiKey("")
                            //.SetDatabaseUrl("Firebase-Database-Url")
                            .SetGcmSenderId("")
                            .Build();
    

    Then , my AndroidManifest looks like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.test" android:installLocation="auto">
        <uses-sdk android:minSdkVersion="15" />
        <application android:label="Test">
            <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
            <!-- [START firebase_service] -->
            <service android:name=".MyFirebaseMessagingService">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT" />
                </intent-filter>
            </service>
            <!-- [END firebase_service] -->
            <!-- [START firebase_iid_service] -->
            <service android:name=".MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
                </intent-filter>
            </service>
            <!-- [END firebase_iid_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>
        </application>
        <permission android:name="com.amazonaws.sns.permission.C2D_MESSAGE" />
        <uses-permission android:name="com.amazonaws.sns.permission.C2D_MESSAGE" />
        <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.GET_ACCOUNTS" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    </manifest>
    

    In the console logs:

    09-13 13:13:33.181 D/FirebaseApp( 2188): com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
    09-13 13:13:33.187 W/InstanceID/Rpc( 2188): Failed to resolve REGISTER intent, falling back
    09-13 13:13:33.189 W/InstanceID/Rpc( 2188): Both Google Play Services and legacy GSF package are missing
    09-13 13:13:33.190 D/FirebaseApp( 2188): com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
    09-13 13:13:33.192 D/FirebaseApp( 2188): com.google.android.gms.measurement.AppMeasurement is not linked. Skipping initialization.
    
  • MikePetersMikePeters USMember ✭✭

    Here is the code I used to get it working:

    MainActivity.cs

    using System;
    using Android.App;
    using Android.Content.PM;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using Firebase;
    using Firebase.Auth;
    using Firebase.Iid;
    using Firebase.Messaging;
    using Android.Gms.Tasks;
    using System.Threading;
    
    namespace MyProject.Mobile.Droid
    {
        [Activity(Label = "MyProject.Mobile", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
        public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
            private FirebaseAuth _auth;
    
            protected override void OnCreate(Bundle bundle)
            {
                TabLayoutResource = Resource.Layout.Tabbar;
                ToolbarResource = Resource.Layout.Toolbar;
    
                base.OnCreate(bundle);
    
                global::Xamarin.Forms.Forms.Init(this, bundle);
                LoadApplication(new App());
    
                FirebaseOptions options = new FirebaseOptions.Builder()
                .SetApplicationId(Settings.FirebaseAppId)
                .SetApiKey(Settings.FirebaseApiKey)
                .SetGcmSenderId(Settings.GcmSenderId)
                .SetDatabaseUrl(Settings.FirebaseDatabaseUrl)
                .SetStorageBucket(Settings.FirebaseStorageBucket)
                .Build();
    
                FirebaseApp app = FirebaseApp.InitializeApp(Android.App.Application.Context, options);
    
                _auth = FirebaseAuth.Instance;
                _auth.AuthState += AuthStateChanged;
    
                CheckUserAuthentication();
            }
    
            void CheckUserAuthentication()
            {
                if (_auth.CurrentUser != null)
                {
    
                }
                else
                {
                    AuthCredential credential = EmailAuthProvider.GetCredential("[email protected]", "mypassword");
                    _auth.SignInWithCredential(credential).AddOnCompleteListener(new SigninCompleteListener());
                }
            }
    
            void AuthStateChanged(object sender, FirebaseAuth.AuthStateEventArgs e)
            {
                var user = e.Auth.CurrentUser;
                if (user != null)
                {
                    FirebaseMessaging.Instance.SubscribeToTopic("myproject-news");
                }
                else
                {
    
                }
            }
        }
    
        class SigninCompleteListener : Java.Lang.Object, IOnCompleteListener
        {
            public void OnComplete(Android.Gms.Tasks.Task task)
            {
                if (task.IsSuccessful)
                {
    
                }
                else
                {
    
                }
            }
        }
    }
    

    MyFirebaseInstanceIdService.cs

    using System;
    using Android.App;
    using Firebase.Iid;
    
        [Service]
        [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
        public class MyFirebaseInstanceIdService : FirebaseInstanceIdService
        {
            const string TAG = "MyFirebaseInstanceIdService";
    
            public override void OnTokenRefresh()
            {
                var refreshedToken = FirebaseInstanceId.Instance.Token;
                Android.Util.Log.Debug(TAG, "Refreshed token: " + refreshedToken);
                SendRegistrationToServer(refreshedToken);
            }
    
            void SendRegistrationToServer(string token)
            {
    
            }
        }
    

    MyFirebaseMessagingService.cs

    using System;
    using Android.App;
    using Android.Content;
    using Android.Media;
    using Android.Support.V4.App;
    using Firebase.Messaging;
    
    
        [Service]
        [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
        public class MyFirebaseMessagingService : FirebaseMessagingService
        {
            const string TAG = "MyFirebaseMessagingService";
    
            public override void OnMessageReceived(RemoteMessage message)
            {
                Android.Util.Log.Debug(TAG, "From: " + message.From);
                Android.Util.Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
            }
    
            void SendNotification(string messageBody)
            {
                var intent = new Intent(this, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop);
                var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
    
                var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                var notificationBuilder = new NotificationCompat.Builder(this)
                    //.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
                    .SetContentTitle("FCM Message")
                    .SetContentText(messageBody)
                    .SetAutoCancel(true)
                    .SetSound(defaultSoundUri)
                    .SetContentIntent(pendingIntent);
    
                var notificationManager = NotificationManager.FromContext(this);
    
                notificationManager.Notify(0, notificationBuilder.Build());
            }
        }
    

    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myproject.android">
        <uses-sdk android:minSdkVersion="15" />
        <application android:label="MyProject">
    
        <service android:name="MyFirebaseInstanceIdService" android:exported="true">
          <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
          </intent-filter>
        </service>
        <service android:name="MyFirebaseMessagingService" android:exported="true">
          <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_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>
    
      </application>
    </manifest>
    
  • MikePetersMikePeters USMember ✭✭
    edited September 2016

    And here are the package versions:

    <?xml version="1.0" encoding="utf-8"?>
    <packages>
      <package id="PCLCrypto" version="0.5.0.14108" targetFramework="monoandroid60" />
      <package id="SQLite.Net.Core-PCL" version="3.1.1" targetFramework="monoandroid60" />
      <package id="SQLite.Net-PCL" version="3.1.1" targetFramework="monoandroid60" />
      <package id="Validation" version="2.0.4.14103" targetFramework="monoandroid60" />
      <package id="Xam.Plugins.Settings" version="2.5.0-beta8" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.Design" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.v4" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.v7.CardView" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.v7.RecyclerView" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Android.Support.Vector.Drawable" version="23.3.0" targetFramework="monoandroid60" />
      <package id="Xamarin.Auth" version="1.3.1.1" targetFramework="monoandroid60" />
      <package id="Xamarin.Firebase.Auth" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.Firebase.Auth.Common" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.Firebase.Auth.Module" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.Firebase.Common" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.Firebase.Iid" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.Firebase.Messaging" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.Forms" version="2.2.0.18-pre3" targetFramework="monoandroid60" />
      <package id="Xamarin.GooglePlayServices.Base" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.GooglePlayServices.Basement" version="32.4.0-beta2" targetFramework="monoandroid60" />
      <package id="Xamarin.GooglePlayServices.Tasks" version="32.4.0-beta2" targetFramework="monoandroid60" />
    </packages>
    
  • brianduccabrianducca ARMember ✭✭

    @MikePeters thanks for sharing your code! I've run it and still not working, the logs give me the same errors.
    One thing i do not see in your code is in MainActivity.cs

    System.Threading.Tasks.Task.Run(() => {
                    var instanceID = FirebaseInstanceId.Instance;
                    instanceID.DeleteInstanceId();
                    var iid1 = instanceID.Token;
                    var iid2 = instanceID.GetToken(Settings.GcmSenderId, FirebaseMessaging.InstanceIdScope);
                    Console.WriteLine("Iid1: {0}, iid2: {1}", iid1, iid2);
                });
    

    Another thing,have you done any special configuration on Firebase?
    Thanks!

  • MikePetersMikePeters USMember ✭✭
    edited September 2016

    @brianducca said:
    @MikePeters thanks for sharing your code! I've run it and still not working, the logs give me the same errors.
    One thing i do not see in your code is in MainActivity.cs

    System.Threading.Tasks.Task.Run(() => {
                    var instanceID = FirebaseInstanceId.Instance;
                    instanceID.DeleteInstanceId();
                    var iid1 = instanceID.Token;
                    var iid2 = instanceID.GetToken(Settings.GcmSenderId, FirebaseMessaging.InstanceIdScope);
                    Console.WriteLine("Iid1: {0}, iid2: {1}", iid1, iid2);
                });
    

    Another thing,have you done any special configuration on Firebase?
    Thanks!

    Make sure you add Certificate Fingerprint on Project Settings > General
    Use the App Id from that same page.
    And use Server Key and Sender Id from Project Settings > Cloud Messaging

  • brianduccabrianducca ARMember ✭✭

    @MikePeters yes, i've added my debug certificate fingerprint in the firebase project & all the firebase data is correct.

    BTW , the class FirebaseAuth, the ide doesn't recognize it. But i guess that oAuth is an extra that you added.
    I'm still getting FirebaseApp initialization unsuccessful

  • brianduccabrianducca ARMember ✭✭
    edited September 2016

    Hello guys, i've solved Firebase Initilization unsuccessful.
    Go to Resources/values in your .droid project.
    add a file named values.xml and fill with your google-services.json data or get it from firebase console.

    <?xml version="1.0" encoding="utf-8" ?>
    <resources>
      <string name="default_web_client_id" translatable="false"></string>
      <string name="gcm_defaultSenderId" translatable="false"></string>
      <string name="firebase_database_url" translatable="false"></string>
      <string name="google_app_id" translatable="false"></string>
      <string name="google_api_key" translatable="false"></string>
      <string name="google_storage_bucket" translatable="false"></string>
    </resources>
    

    Now, i'm having this issue

    09-14 12:53:00.618 W/InstanceID/Rpc( 3267): Failed to resolve REGISTER intent, falling back
    09-14 12:53:00.626 W/InstanceID/Rpc( 3267): Both Google Play Services and legacy GSF package are missing
    

    @JonathanDick @JamesMontemagno do you know why?

  • MikePetersMikePeters USMember ✭✭
    edited September 2016

    @JonathanDick said:
    I've updated the github issue with the fix: https://github.com/xamarin/GooglePlayServicesComponents/issues/20

    @JonathanDick,
    Thanks for your effort getting this fixed.
    It would be extremely helpful if you or someone from Xamarin could tell us more about the future plans for the Xamarin Firebase components so we can plan accordingly:

    1. It looks like Xamarin.Firebase.Auth, Xamarin.Firebase.Messaging, etc only support Android. Is this true? Are there plans to support IOS? If so, will it be a separate component, and what is the time frame?

    2. I notice there is another .NET Firebase component https://github.com/step-up-labs/firebase-authentication-dotnet that looks like it works in my PCL project. Which I guess means I could create a Login page in my PCL project that is shared across all platforms. Would this approach work as well?

    Thanks!

  • brianduccabrianducca ARMember ✭✭
    edited September 2016

    @MikePeters hey mike, i've solved my issues with firebase but now i'm getting a Java RuntimeException:

    Java.Lang.RuntimeException: Unable to instantiate service com.myapp.test.MyFirebaseInstanceIdService: java.lang.ClassNotFoundException: Didn't find class "com.myapp.test.MyFirebaseInstanceIdService" on path: DexPathList[[zip file "/data/app/com.myapp.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.test-1/lib/x86, /vendor/lib, /system/lib]]

    have you got this issue?

  • MikePetersMikePeters USMember ✭✭
    edited September 2016

    @brianducca said:
    @MikePeters hey mike, i've solved my issues with firebase but now i'm getting a Java RuntimeException:

    Java.Lang.RuntimeException: Unable to instantiate service com.myapp.test.MyFirebaseInstanceIdService: java.lang.ClassNotFoundException: Didn't find class "com.myapp.test.MyFirebaseInstanceIdService" on path: DexPathList[[zip file "/data/app/com.myapp.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.test-1/lib/x86, /vendor/lib, /system/lib]]

    have you got this issue?

    Try setting the name in your androidmanifest like this (without "com.myapp.test")
    <service android:name="MyFirebaseInstanceIdService" android:exported="true">

  • brianduccabrianducca ARMember ✭✭

    @MikePeters i have my manifest in the correct way, like you said before. I don't know why is adding the package name

  • JonathanDickJonathanDick CAXamarin Team, Developer Group Leader Xamurai
    1. Currently yes, there will be separate nuget packages for iOS which @IsraelSoto is currently working on.
    2. We don't have anything to do with that project, but it looks interesting. I can't really comment on using it or how it would work.

    @MikePeters said:

    @JonathanDick said:
    I've updated the github issue with the fix: https://github.com/xamarin/GooglePlayServicesComponents/issues/20

    @JonathanDick,
    Thanks for your effort getting this fixed.
    It would be extremely helpful if you or someone from Xamarin could tell us more about the future plans for the Xamarin Firebase components so we can plan accordingly:

    1. It looks like Xamarin.Firebase.Auth, Xamarin.Firebase.Messaging, etc only support Android. Is this true? Are there plans to support IOS? If so, will it be a separate component, and what is the time frame?

    2. I notice there is another .NET Firebase component https://github.com/step-up-labs/firebase-authentication-dotnet that looks like it works in my PCL project. Which I guess means I could create a Login page in my PCL project that is shared across all platforms. Would this approach work as well?

    Thanks!

  • MikePetersMikePeters USMember ✭✭

    @JonathanDick said:
    1. Currently yes, there will be separate nuget packages for iOS which @IsraelSoto is currently working on.
    2. We don't have anything to do with that project, but it looks interesting. I can't really comment on using it or how it would work.

    I guess I don't understand why there isn't a way to do this with shared code in a PCL project. With separate packages, we need to create all kinds of custom platform code (which defeats the purpose of Xamarin in the first place) Maybe I just don't understand completely and maybe this is the only way to do it.

  • brianduccabrianducca ARMember ✭✭

    @JonathanDick hey! according to your answer to solve the last issue , i've added this:

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

    But i'm getting build errors with this line
    <category android:name="${applicationId}" />

    1>  obj\Debug\android\manifest\AndroidManifest.xml:30: Tag <category> attribute name has invalid character '$'.
    1>C:\Program Files (x86)\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(1832,3): error MSB6006: "aapt.exe" exit with code 1.
    

    And if i erase that line , the build works, but i get this:

    Java.Lang.RuntimeException: Unable to instantiate service com.myapp.test.MyFirebaseInstanceIdService: java.lang.ClassNotFoundException: Didn't find class "com.myapp.test.MyFirebaseInstanceIdService" on path: DexPathList[[zip file "/data/app/com.myapp.test-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.test-1/lib/x86, /vendor/lib, /system/lib]]

  • JonathanDickJonathanDick CAXamarin Team, Developer Group Leader Xamurai

    @brianducca looks like maybe you're on an old version of xamarin.android?

  • brianduccabrianducca ARMember ✭✭

    @JonathanDick said:
    @brianducca looks like maybe you're on an old version of xamarin.android?

    @JonathanDick I'm running X.Android 7.0 now, and the build error is gone , but i'm still getting the java runtime exception

  • JonathanDickJonathanDick CAXamarin Team, Developer Group Leader Xamurai

    @brianducca not sure about that one, maybe your code is getting linked out? try turning off linking?

  • brianduccabrianducca ARMember ✭✭

    @JonathanDick i have linked option in "none", so it's not linking, i can't even get a token

  • CraigSchulteCraigSchulte USMember
    edited September 2016

    FYI, this stuff has to go inside the application tag in your manifest, I didn't do that right away and it caused me lots of headaches trying to figure out what was wrong:

    <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>
    
Sign In or Register to comment.