Firebase Message + Firebase Analytics in Xamarin
Analytics is one of the most useful things out there when it comes to app development and user engagement. Since most apps are showing these days adds is important to learn where are your users spending more time and where can you improve your content.
In this tutoríal I would be sharing two firebase services that are important for new apps, one would be cloud messaging and the other one will be firebase analytics.
Let’s start with firebase analytics. In the Android project, we are going to create a new class. This new class will contain all the relevant information to use analytics, we will need to install first the NUGET package Xamarin.Firebase.Analytics.
Also you need to have a Firebase Console Account you can go here to create the new account.
After we are done creating our account and adding our app, we will get a google JSON file that we will download and add to our Android Project or iOS. It is important to select properties to build action Google Services JSON.
Now we are going to install the NuGet
t packages for Firebase Push Message and Firebase Analytics on the Android or iOS project. We won’t need any more packages.
Let’s create a class in our Android Project in my app the name of the class is FirebaseAnalytic
And simply paste the following code changing the name of the app to use your own
This code is using the new approach use by Google. So the code is not deprecated or obsolete. It is basically an injection with an interface that will be on the Xamarin Project. The LogEvent will save the event we create to display that information on the firebase console, you can add events to buttons, page loads, and many other events.
I create a folder named Services and a new interface called IFirebaseAnalytics and paste this code. This on the Xamarin Project
Then since I used MVVM pattern I need to log events on my buttons command or on my constructor. In this case for a simple button, I add the following code.
Now we are all done. No more code to add it will take 24 hours to show on Analitycs.
This one is a little bit tricky. We create in our Android or iOS project this class.
The OnNewToken is the correct way to implement the Firebase Message in Xamarin Forms. Since the
public override void OnTokenRefresh() is now obsolete and deprecated. Visit this to read about it.
Now on the Manifest, we need to add some lines to call the service on start and define the icon for the Notifications.
And that’s all. We don’t need more since the new Service is more simple to deploy.
If you are using like me R8 and D8 then your R8 Proguard File to avoid errors should be like this.
And that’s all, now test your notifications and visit your Firebase Console to see your analytics data. Remember to deploy your app on a physical device.
If you want to use OAuth with Firebase you can look here.