Forum Xamarin.Android

Firebase configuration

13»

Posts

  • RainerMagerRainerMager JPMember ✭✭✭

    I'm only trying to use Firebase Analytics and am running into a problem, although I might have just solved it.

    In a release build I'm seeing these messages in the ADB log, although they don't show up in a debug build:
    09-07 21:13:22.689 E/FA ( 5411): Task exception on worker thread: java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist. : com.google.android.gms.measurement.internal.zzt.zzbpu(Unknown Source)

    I just managed to get rid of this by calling FirebaseApp app = FirebaseApp.InitializeApp(this, options);. I find it very strange that this is needed in release builds only.

    Anyone have any ideas?

  • I'm trying to use an example from here:
    https://github.com/xamarin/GooglePlayServicesComponents/tree/v9.4.0/firebase-messaging/samples

    I’ve discovered the next problem. When the project is launched on the device for the first time everything works fine, all of the methods and event handlers are invoked, including «OnMessageReceived» method. I’m using Firebase console for notification type message sending.
    When I launch the same project for the second time on the device (emulator), the next error message appears at the console - "token registration period has expired". In the case when the application is completely removed from the device, then at the next launch the registration token is updated through the method “OnTokenRefresh” and after that all of the methods are invoked fine until the next restart.

    At the same time when I launch a similar example project for Android Studio from here: (https://github.com/firebase/quickstart-android/tree/master/messaging), there is no such problem.

  • RainerMagerRainerMager JPMember ✭✭✭

    @MikePeters said:
    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.

    I think the problem is that Google only provides native libraries (separate for iOS and Android) and doesn't document a generic API for Firebase. Ideally they would provide a full REST interface or something and then this would be possible.

    Having said that, I think it should be possible to make a PCL library that is an abstract class and have the two platform version implement that. You could then just reference that PCL library in all of your common code.

  • MarkCerezoMarkCerezo USMember ✭✭

    Hi Guys do you have any working method for this?

  • ArramusArramus USMember

    @brianducca said:
    @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]]

    Does anyone have a solution/reasoning behind this run-time exception, I'd very much like to get fire base going with my application, we have the exact same exception and had no luck finding a fix.

  • FrancescoCremaFrancescoCrema USMember ✭✭

    @DmitryBrezgin said:
    I'm trying to use an example from here:
    https://github.com/xamarin/GooglePlayServicesComponents/tree/v9.4.0/firebase-messaging/samples

    I’ve discovered the next problem. When the project is launched on the device for the first time everything works fine, all of the methods and event handlers are invoked, including «OnMessageReceived» method. I’m using Firebase console for notification type message sending.
    When I launch the same project for the second time on the device (emulator), the next error message appears at the console - "token registration period has expired". In the case when the application is completely removed from the device, then at the next launch the registration token is updated through the method “OnTokenRefresh” and after that all of the methods are invoked fine until the next restart.

    At the same time when I launch a similar example project for Android Studio from here: (https://github.com/firebase/quickstart-android/tree/master/messaging), there is no such problem.

    I'm facing a similar issue: my token works for the first time I try to send a Firebase message, then, after the second trial, Xamarin warns me that the token is unregistered.
    Do you have any idea why it could happen?

  • @FrancescoCrema said:

    @DmitryBrezgin said:
    I'm trying to use an example from here:
    https://github.com/xamarin/GooglePlayServicesComponents/tree/v9.4.0/firebase-messaging/samples

    I’ve discovered the next problem. When the project is launched on the device for the first time everything works fine, all of the methods and event handlers are invoked, including «OnMessageReceived» method. I’m using Firebase console for notification type message sending.
    When I launch the same project for the second time on the device (emulator), the next error message appears at the console - "token registration period has expired". In the case when the application is completely removed from the device, then at the next launch the registration token is updated through the method “OnTokenRefresh” and after that all of the methods are invoked fine until the next restart.

    At the same time when I launch a similar example project for Android Studio from here: (https://github.com/firebase/quickstart-android/tree/master/messaging), there is no such problem.

    I'm facing a similar issue: my token works for the first time I try to send a Firebase message, then, after the second trial, Xamarin warns me that the token is unregistered.
    Do you have any idea why it could happen?

    Actually I don't know what the problem is. But I found out that in Release mode there is no such issue (though there is no possibility for debugging...)

  • FrancescoCremaFrancescoCrema USMember ✭✭

    Thanks Dmitry for sharing! Seems to work!
    I have an issue: where and how do you initialize firebaseApp?

    This is my code in MainActivity onCreate
    if (firebaseApp == null) { var FirebaseOptions = new FirebaseOptions.Builder() .SetApplicationId("1:587449258098:android:bd6cc7524f719ace") .SetApiKey("AIzaSyBPZD3af-XusKe9OSGw4dlaLfpRMDykUQQ") .SetGcmSenderId("587449258098") .SetDatabaseUrl("https://powerme-7ca94.firebaseio.com") .SetStorageBucket("powerme-7ca94.appspot.com") .Build(); firebaseApp = FirebaseApp.InitializeApp(Android.App.Application.Context, FirebaseOptions); firebaseAppInitialized = true; }

    But when the app goes in background and I open it again, it somehow tries to initialize firebaseApp again, giving me an exception. How can I check it?
    Do I have to place my code somewhere else?
    Thanks

  • NEkmanNEkman SEMember

    @DmitryBrezgin said:
    Actually I don't know what the problem is. But I found out that in Release mode there is no such issue (though there is no possibility for debugging...)

    Thanks for pointing out that FCM does work in a Release app! I'd just like to highlight this for others reading this thread as I almost missed it. I had the same problems, with it only working after a fresh install, in a Debug environment.

  • anybody know if push notifications using firebase is working now?

  • @FrancescoCrema said:
    Thanks Dmitry for sharing! Seems to work!
    I have an issue: where and how do you initialize firebaseApp?

    This is my code in MainActivity onCreate
    if (firebaseApp == null) { var FirebaseOptions = new FirebaseOptions.Builder() .SetApplicationId("1:587449258098:android:bd6cc7524f719ace") .SetApiKey("AIzaSyBPZD3af-XusKe9OSGw4dlaLfpRMDykUQQ") .SetGcmSenderId("587449258098") .SetDatabaseUrl("https://powerme-7ca94.firebaseio.com") .SetStorageBucket("powerme-7ca94.appspot.com") .Build(); firebaseApp = FirebaseApp.InitializeApp(Android.App.Application.Context, FirebaseOptions); firebaseAppInitialized = true; }

    But when the app goes in background and I open it again, it somehow tries to initialize firebaseApp again, giving me an exception. How can I check it?
    Do I have to place my code somewhere else?
    Thanks

    I'm using the sample project from Xamarin as is, without any changes in code (except google-services.json file). I guess that the main step is not to forget to switch the build action of this file to "GoogleServicesJson" mode.

  • I'm trying to use sample from v9.4.0 and v9.6.1 and both of them a working correctly. How about If the application is in the foreground handle both data and notification messages here?
    Anybody implement this code in the OnMessageReceived method?

  • MikePetersMikePeters USMember ✭✭

    @JonathanDick said:
    1. Currently yes, there will be separate nuget packages for iOS which @IsraelSoto is currently working on.

    Jonathan,
    A while back I sent a message to @IsraelSoto inquiring about an iOS Firebase package, but never received a response back. Do you have any more information about a timeline for this?
    Thanks

  • JonathanDickJonathanDick CAXamarin Team, Developer Group Leader Xamurai

    @MikePeters there are several of them up already: https://www.nuget.org/packages?q=firebase+ios

  • RobinMRobinM USMember

    how to implement app server for FCM?

  • MikePetersMikePeters USMember ✭✭

    @JonathanDick said:
    @MikePeters there are several of them up already: https://www.nuget.org/packages?q=firebase+ios

    Thanks. I am currently testing the Firebase Cloud Messaging for IOS component and it looks like it might work fine. I appreciate your answers to my questions, as it sometimes seems difficult to get answers.

    I had one other question that you might know the answer to:
    I am not sure of the exact versions, but If I am not mistaken, Xamarin.Firebase.Messaging requires GooglePlayServices version 32+, yet Xamarin.Forms.Maps requires GooglePlayServices version =29... so if I use the Xamarin.Firebase.Messaging package, I am not able to use other packages (like Xamarin.Forms.Maps) Is this correct? Is there any way around this?

  • MikePetersMikePeters USMember ✭✭

    Thanks. I am currently testing the Firebase Cloud Messaging for IOS component and it looks like it might work fine. I appreciate your answers to my questions, as it sometimes seems difficult to get answers.

    I had one other question that you might know the answer to:
    I am not sure of the exact versions, but If I am not mistaken, Xamarin.Firebase.Messaging requires GooglePlayServices version 32+, yet Xamarin.Forms.Maps requires GooglePlayServices version =29... so if I use the Xamarin.Firebase.Messaging package, I am not able to use other packages (like Xamarin.Forms.Maps) Is this correct? Is there any way around this?

    Is Xamarin working on making these packages compatible with other Xamarin packages? I can get this working but as soon as I add other things, like Google Maps, it blows my project up. This is the most fragile development environment I've ever seen. I don't see how Xamarin saves time over just building separate IOS and Android projects natively. I am wishing now I had gone down that path in the first place. It would be nice to get some kind of feedback. Is there work being done to make this more stable or did all the Xamarin developers go on vacation after the Microsoft buyout?

  • PhilippSumiPhilippSumi USMember ✭✭✭

    Unfortunately, I'm with Mike on this. There's really way too many threads here that end up in plain frustration over half-baked offerings that seem to somehow work, but eventually end up in dead-ends, and it's starting to echo into the internet as well, changing the general perception of the tech. There needs to be a strong investment in getting the existing code base to work, and integrate with packages that are just an Android / iOS developer's daily bread :/

  • UmutBebekUmutBebek TRMember ✭✭

    Hi guys, i will try to tell my way to implement push notifications, it works on LGE Nexus 5 with Android 6.0 on it.
    I will not go over how to create an app for FCm and get those SenderId etc. :)

    First of all my app is working on
    Xamarin.Forms 2.3.3.168
    Xamarin.Firebase.Common
    Xamarin.Firebase.Lid
    Xamarin.Firebase.Messaging on 32.940.0-beta3
    Xamarin.GooglePlayServices.Basement
    Xamarin.GooglePlayServices.Tasks on 32.940.0-beta3

    I'm using my server to send push notification with asp.net with PushSharp 4.0.10. I will paste a code sample too for it.

    First of all you have to add two classes (i wrote them in a single file) which inherits Firebase classes to your android project anywhere like this:

    `
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Android.App;
    using Android.Content;
    using Android.Media;
    using Android.Support.V7.App;
    using ContentCloud.Mobile.Data;
    using ContentCloud.Mobile.Droid;
    using ContentCloud.Mobile.Helpers;
    using ContentCloud.Mobile.Observe;
    using ContentCloudModels.Api.Rest.User;
    using Firebase.Iid;
    using Firebase.Messaging;

    namespace ContentCloud.Mobile.Service
    {
    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIdService : FirebaseInstanceIdService
    {
    const string TAG = "MyFirebaseIIDService";

        //I am getting token on my code so i commented out this code, if you want to take it here you can uncomment; it fires too.
        //public override void OnTokenRefresh()
        //{
        //    // Get updated InstanceID token.
        //    var refreshedToken = FirebaseInstanceId.Instance.Token;
        //    //Android.Util.Log.Debug(TAG, "Refreshed token: " + refreshedToken);
    
        //    MyFirebaseMessagingService.RegisterForAndroid(refreshedToken);
        //}
    }
    
    [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);
    
        //I am playing a sound if i receive a notification, you can comment here if you do not want
            var player = MediaPlayer.Create(this, Resource.Raw.wet);
            player.Start();
    
           //I'm taking my custom values from the message array, you can see the on my send push notification code
           //for pushSharp on the server side :)
            string notificationTypeId;
            message.Data.TryGetValue("NTID", out notificationTypeId);
            string helperValues;
            message.Data.TryGetValue("HV", out helperValues);
    
           //I am converting message array to my custom class, so i can easily manage the notification in my app
           //NotificationMessageDto is my custom class, just write your own
           //AppSettings.ReceivedNotification is my static propery to hold this class, just to get message from views
            AppSettings.ReceivedNotification = new NotificationMessageDto
            {
                Title = message.GetNotification().Title,
                Body = message.GetNotification().Body,
                NotificationTypeId = Convert.ToInt32(notificationTypeId),
                HelperValues = helperValues,
                NavigateNow = false //message came when app was on foreground
            };
            //it is a simple 'Singleton' pattern class and implementations to notify my home page that new message has arrived
           //So my home page listens to this class and learns that a new notification has arrived, So I'm just processing
       //the AppSettings.ReceivedNotification (static NotificationMessageDto property) according to it's content
           //You have to write your own logic of course :)
            ObserveManager.Instance.SendMessage(ObserveType.RemoteNotification, null);
        }
    
        //This class sends the token to my server api, you have to write your custom code if you want to hold
        //device tokens on server side 
       //I'm calling this static method where i receive token
        public static void RegisterForAndroid(string deviceToken)
        {
            //I'm calling json api methods etc. here
        }
    }
    

    }
    `

    I'm calling below code on my homePage's class definition, for example onAppearing maybe, it's up to you, So when user
    opens the app, token will be taken and send to server.

    `
    var options = new FirebaseOptions.Builder()
    .SetApplicationId("YOURAPPID") //6 digits i think
    .SetApiKey("YOURAPIKEY")
    //.SetDatabaseUrl(Keys.Firebase.Database_Url) //i do not use db
    .SetGcmSenderId("YOURSENDERID") //13 digits i think
    //.SetStorageBucket(Keys.Firebase.StorageBucket) //i do not use storage
    .Build();

           try
            {  //I'm calling Initialize firebase app. It throws exception if it's already initilized. I'm so lazy so i did not check
               //if it is already initialized :) You can check if you want
                FirebaseApp app = FirebaseApp.InitializeApp(Forms.Context, options);
            }
            catch { }
    
            // Generate token in background thread and call my static method to pass it to server as defined above code
            Task.Factory.StartNew(() =>
            {
                try
                {
                    var instanceID = FirebaseInstanceId.Instance;
                    //var oldToken = instanceID.Token;
                    var newToken = instanceID.GetToken("YOURSENDERID", Firebase.Messaging.FirebaseMessaging.InstanceIdScope);
                    //System.Diagnostics.Debug.WriteLine("Iid1: {0}, iid2: {1}", oldToken, newToken);
                    //!!!!If you want to delete old token, you have to write yourcustom code. I'm deleting old tokens 
                    //on my static method, because it may create different tokens for same device and all of them may be
                    //active :)
                    MyFirebaseMessagingService.RegisterForAndroid(newToken); //I'm sending token to my server
                }
                catch (Exception ex)
                {
                    DialogHelper.ShowError("Error registering push notifications to Content Cloud Server: " + ex.Message);
                }
            });
    

    `

    Above code only receives foreground notifications. If the appis on background, user taps the message on notification areaand navigates to app right? So we have to get notification info on app start.

    !!!!I'm using a splash screen so i had to write Intent.Extras code to my SplashScreen activity. If you do not have a splash screen just add this code (after base.OnCreate(bundle)) to your MainActivity class.

    `
    [Activity(Icon = "@drawable/icon", MainLauncher = true, NoHistory = true, Theme = "@style/Theme.Splash", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class SplashScreen : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
    protected override void OnCreate(Bundle bundle)
    {
    base.OnCreate(bundle);

        //just copy this block if you want to move it to MainActivity
            if (Intent.Extras != null)
            {
                try
                {   //!!I'm just reading myvalues from data and creating a notification DTO class like before
                    //I think the title and body of the notication will not be send here (by android os). So ypu can not
                    //read them here. So I'm justsending those values in a seperate object and taking here, please
                    //look to the PushSharp example.
                    //And i'm taking it to a static property to use later on my app
                    AppSettings.ReceivedNotification = new NotificationMessageDto
                    {
                        Title = Intent.Extras.GetString("TTL"),
                        Body = Intent.Extras.GetString("BDY"),
                        NotificationTypeId = Convert.ToInt32(Intent.Extras.GetString("NTID")),
                        HelperValues = Intent.Extras.GetString("HV"),
                        NavigateNow = true //user tapped notification while app on background
                    };
                }
                catch
                {
                }
            }
    
            //Splash Screen's own code.Do not copy to MainActivity if you want to move this code.
            var intent = new Intent(this, typeof(MainActivity));
            StartActivity(intent);
            Finish();
        }
    }
    

    `

    And the server side code to send push notification for PushSharp:

    `
    var config = new GcmConfiguration("YOURSENDERID", "YOURAPIKEY", null);
    config.GcmUrl = "https://fcm.googleapis.com/fcm/send"; //!!!!!gmc changed to fcm

               var  _gcmBroker = new GcmServiceBroker(config);
    
                // Wire up events
                _gcmBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
    
                    aggregateEx.Handle(ex =>
                    {
                        //log if you want
    
                        // Mark it as handled
                        return true;
                    });
                };
    
                _gcmBroker.OnNotificationSucceeded += notification =>
                {
                    //log if you want
                };
    
                // Start the broker
                _gcmBroker.Start();
    
               _gcmBroker.QueueNotification(new GcmNotification
                {
                    RegistrationIds = new List<string> { token }, //this is the device token that you want to send notification
                    Notification = JObject.Parse( //notification entry holds the notificationinfo to show
                        "{" +
                            "\"title\" : \"" + title + "\"," + //title shown on screen
                            "\"body\" : \"" + body + "\"," + //body(message) shown on screen
                            "\"sound\" : \"wet.caf\"" + //my custom sound to play (this must be on android project resources :) ) 
                        "}") ,
                    Data = JObject.Parse( //Data holds the custom information about my notification. I'm sending notification typeInfo and some helperValues string to understand and take some actions on device :)
                        "{" +                            
                            "\"TTL\" : \"" + title + "\"," + //we can not read title or body from the notification propery when user taps a notification when app is on background, so i'm sending same values via Data too; please look to Intent.Extras code for android
                            "\"BDY\" : \"" + body+ "\"," +
                            "\"NTID\" : \"" + myNotificationTypeId + "\"," + //so i can undestand this notification what for?
                            "\"HV\" : \"" + myHelperValues + "\"" + //and other helper values like ViewName or a RecordId etc.
                        "}")
                });
    

    `

    Hope this helps everyone.

  • UmutBebekUmutBebek TRMember ✭✭

    !!!!do not use below code to get token. I think android may create another token that is not registered for pushNotifications and notification center returns "Unregistered registration token" error (this tokenusualy works but sometimes give errors, so it is not safe to use it)

            // Generate token in background thread and call my static method to pass it to server as defined above code
            Task.Factory.StartNew(() =>
            {
                try
                {
                    var instanceID = FirebaseInstanceId.Instance;
                    //var oldToken = instanceID.Token;
                    var newToken = instanceID.GetToken("YOURSENDERID", Firebase.Messaging.FirebaseMessaging.InstanceIdScope);
                    //System.Diagnostics.Debug.WriteLine("Iid1: {0}, iid2: {1}", oldToken, newToken);
                    //!!!!If you want to delete old token, you have to write yourcustom code. I'm deleting old tokens 
                    //on my static method, because it may create different tokens for same device and all of them may be
                    //active :)
                    MyFirebaseMessagingService.RegisterForAndroid(newToken); //I'm sending token to my server
                }
                catch (Exception ex)
                {
                    DialogHelper.ShowError("Error registering push notifications to Content Cloud Server: " + ex.Message);
                }
            });
    

    `

    Just uncomment the
    //public override void OnTokenRefresh()
    //{
    // // Get updated InstanceID token.
    // var refreshedToken = FirebaseInstanceId.Instance.Token;
    // //Android.Util.Log.Debug(TAG, "Refreshed token: " + refreshedToken);

    //    MyFirebaseMessagingService.RegisterForAndroid(refreshedToken);
    //}
    

    code on MyFirebaseIdService and use that refreshedToken instead. That token works all the time.

  • ShahriatHossainShahriatHossain USMember ✭✭

    I am using firebase cloud messaging for my xamarin.ios project and I am following this component integration tutorial:
    https://components.xamarin.com/gettingstarted/firebaseioscloudmessaging

    push notification working great for ios 9 but it doesn't work for ios 10 because I have found two codes doesn't match with my current setting below on my FinishedLaunching method:

    UNUserNotificationCenter.Current.Delegate = this;
    Messaging.SharedInstance.RemoteMessageDelegate = this;

    after finding an enhancement from xamarin official site here https://developer.xamarin.com/guides/ios/platform_features/introduction-to-ios10/user-notifications/enhanced-user-notifications/ I have updated my code for this code below:

    from
    UNUserNotificationCenter.Current.Delegate = this;
    to
    UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

    I am still facing the problem with this code : Messaging.SharedInstance.RemoteMessageDelegate = this;
    do you have any idea what should be the enhancement for this above single code?

  • SureshValle480SureshValle480 USMember ✭✭
    edited January 2017

    Hi @RainerMager I created a XML file in my Android project's Resources/values folder called goog_svcs_json.xml and added keys has like below

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

    And Added below code Oncreate Method

    FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.GetInstance(context);
                Bundle bundle = new Bundle();
                bundle.PutString(FirebaseAnalytics.Param.ItemId, "Test_ID");
                bundle.PutString(FirebaseAnalytics.Param.ItemName, "Test_NAME");
                bundle.PutString(FirebaseAnalytics.Param.ItemCategory, "Test_image");
                firebaseAnalytics.LogEvent("Test_event", bundle);
    

    But analytics not showing in firebase console, Please let me know what i did wrong?

  • SureshValle480SureshValle480 USMember ✭✭
    edited January 2017

    Hi @RainerMager I created a XML file in my Android project's Resources/values folder called goog_svcs_json.xml and added below keys

    google_app_id
    gcm_defaultSenderId
    default_web_client_id
    firebase_database_url
    google_api_key
    google_crash_reporting_api_key

    And Added below code Oncreate Method

    FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.GetInstance(context);
                Bundle bundle = new Bundle();
                bundle.PutString(FirebaseAnalytics.Param.ItemId, "Test_ID");
                bundle.PutString(FirebaseAnalytics.Param.ItemName, "Test_NAME");
                bundle.PutString(FirebaseAnalytics.Param.ItemCategory, "Test_image");
                firebaseAnalytics.LogEvent("Test_event", bundle);
    

    But analytics not showing in firebase console, Please let me know what i did wrong?

  • KenNickersonKenNickerson USMember ✭✭✭

    @DmitryBrezgin would it be too much to ask to post the url for the sample project. I am finding everything but...

    thanks in advance

  • KenNickersonKenNickerson USMember ✭✭✭

    Specifically looking for the analytics sample project...thanks

  • @KenNickerson said:
    Specifically looking for the analytics sample project...thanks

    I guess you may try this one:
    https://github.com/xamarin/GooglePlayServicesComponents/tree/v10.0.1/analytics/samples

  • sagarkothadiyasagarkothadiya INMember

    Hey Guys , Could you help on this.

    I faced problem with firebase push notification on background.

    i have followed this step.

    1 - I have added needed Packages.

      <package id="Xamarin.Firebase.Common" version="42.1001.0" targetFramework="monoandroid71" />
      <package id="Xamarin.Firebase.Iid" version="42.1001.0" targetFramework="monoandroid71" />
      <package id="Xamarin.Firebase.Messaging" version="42.1001.0" targetFramework="monoandroid71" />
      <package id="Xamarin.Forms" version="2.3.3.193" targetFramework="monoandroid71" />
      <package id="Xamarin.GooglePlayServices.Base" version="42.1001.0" targetFramework="monoandroid71" />
      <package id="Xamarin.GooglePlayServices.Basement" version="42.1001.0" targetFramework="monoandroid71" />
      <package id="Xamarin.GooglePlayServices.Tasks" version="42.1001.0" targetFramework="monoandroid71" />
    

    2 - added google-services.json in Droid root folder.

    3 - Created InstanceID serviece MyFirebaseInstanceIdService.cs

    [Service, IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseInstanceIdService : FirebaseInstanceIdService
    {
    public override void OnTokenRefresh()
    {
    var token = FirebaseInstanceId.Instance.Token;

            // todo
            // 1. check if token has changed
            // 2. if changed communicate it to backend
        }
    }
    

    4- Created MyFirebaseListenerService.cs

    [Service, IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseListenerService : FirebaseMessagingService
    {
    public override void OnMessageReceived(RemoteMessage message)
    {
    base.OnMessageReceived(message);

            var notification = message.GetNotification();
            var title = notification.Title;
            var body = notification.Body;
    
            SendNotification(title, body);
        }
    
        private void SendNotification(string title, string body)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            // intent.PutExtra("launchArguments", "stuff");
    
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
    
            var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
    
            var notificationBuilder =
                new NotificationCompat.Builder(this)
                    .SetSmallIcon(Resource.Drawable.icon)
                    .SetContentTitle(title)
                    .SetContentText(body)
                    .SetAutoCancel(true)
                    .SetSound(defaultSoundUri)
                    .SetContentIntent(pendingIntent);
    
            var notificationManager = NotificationManager.FromContext(this);
            notificationManager.Notify(0, notificationBuilder.Build());
        }
    }
    

    and in my case token generated on token refresh and that token i have used to send notification from firebase console but it display Failed status (Unregistered Token).

    its necessary to add receiver tag In manifest file..??? if yes than how in Visual studio 2015 AndroidManifest.xaml file generated on Debug or Release.

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

    Please Share Proper Step to accomplish firebase pushnotification for background.

    Thanks

  • sagarkothadiyasagarkothadiya INMember

    Hey Guys could you help on this.

    i am facing problem firebase pushnotification for background.

    1- I have add needed Packages

    <package id="Xamarin.Firebase.Common" version="42.1001.0" targetFramework="monoandroid71" /> <package id="Xamarin.Firebase.Iid" version="42.1001.0" targetFramework="monoandroid71" /> <package id="Xamarin.Firebase.Messaging" version="42.1001.0" targetFramework="monoandroid71" /> <package id="Xamarin.Forms" version="2.3.3.193" targetFramework="monoandroid71" /> <package id="Xamarin.GooglePlayServices.Base" version="42.1001.0" targetFramework="monoandroid71" /> <package id="Xamarin.GooglePlayServices.Basement" version="42.1001.0" targetFramework="monoandroid71" /> <package id="Xamarin.GooglePlayServices.Tasks" version="42.1001.0" targetFramework="monoandroid71" />

    2 - I have added google-services.json in Droid root folder.

    3- Created MyFirebaseInstanceIdService.cs

    ` [Service, IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseInstanceIdService : FirebaseInstanceIdService
    {
    public override void OnTokenRefresh()
    {
    var token = FirebaseInstanceId.Instance.Token;

            // todo
            // 1. check if token has changed
            // 2. if changed communicate it to backend
        }
    }`
    

    4 - Created MyFirebaseListenerService.cs

    ` [Service, IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    public class MyFirebaseListenerService : FirebaseMessagingService
    {
    public override void OnMessageReceived(RemoteMessage message)
    {
    base.OnMessageReceived(message);

            var notification = message.GetNotification();
            var title = notification.Title;
            var body = notification.Body;
    
            SendNotification(title, body);
        }
    
        private void SendNotification(string title, string body)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            // intent.PutExtra("launchArguments", "stuff");
    
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
    
            var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
    
            var notificationBuilder =
                new NotificationCompat.Builder(this)
                    .SetSmallIcon(Resource.Drawable.icon)
                    .SetContentTitle(title)
                    .SetContentText(body)
                    .SetAutoCancel(true)
                    .SetSound(defaultSoundUri)
                    .SetContentIntent(pendingIntent);
    
            var notificationManager = NotificationManager.FromContext(this);
            notificationManager.Notify(0, notificationBuilder.Build());
        }
    }`
    

    in my case OnToken refresh token generated but with that token i send message from firebase console but status failed (Unregistered Token).

    is it required to add reciever tag in Manifest file..??? if yes than how in Visual studio 2015 AndroidManifestfile generated on Debug or Release.

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

    Please share proper step to accomplish firebase push notification for background.

    Thanks.

  • jenijeni INMember ✭✭

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

    I am also faced this issue,Have any one got the sollution.

  • PrzemoPrzemo USMember ✭✭

    [Service]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    class MyFirebaseIdService : FirebaseInstanceIdService
    {
    public override void OnTokenRefresh()
    {
    base.OnTokenRefresh();
    Android.Util.Log.Debug("Odświeżony Token:", FirebaseInstanceId.Instance.Token);

        }
    }
    

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT"})]
    class MyFirebaseMessagingService : FirebaseMessagingService
    {
    public override void OnMessageReceived(RemoteMessage message)
    {
    base.OnMessageReceived(message);
    SendNotification(message.GetNotification().Body);
    SyncAsync();
    }

        private void SendNotification(string body)
        {
            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.icoblck)
                .SetContentTitle("")
                .SetContentText(body)
                .SetAutoCancel(true)
                .SetSound(defaultSoundUri)
                .SetContentIntent(pendingIntent);
    
            var notificationManager = NotificationManager.FromContext(this);
            notificationManager.Notify(0, notificationBuilder.Build());
        }
    

    manifest








  • PrzemoPrzemo USMember ✭✭
    edited March 2017

    @Przemo said:








    g

  • PrzemoPrzemo USMember ✭✭

    "






    "

  • PrzemoPrzemo USMember ✭✭

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

  • sagarkothadiyasagarkothadiya INMember

    @jeni said:

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

    I am also faced this issue,Have any one got the sollution.

    i have done with cross platform Plugin . xam.Plugin.Pushnotification. it works well. hope its help you.

  • JoshFeldmanJoshFeldman USMember

    Has anyone got Firebase dynamic links working with Xamarin Android?

Sign In or Register to comment.