My notifications are not coming and I think my code may be correct

1

I made several attempts to send Push Notification and none of them I could see in my App. I always thought until now, that I was wrong. But I followed two step by step and I saw that with the guys it was working and not with me. So I started to think otherwise, that either the firebase did not fire properly or my equipment, for reasons hitherto unknown, is not receiving. How did I come to this conclusion? Is that when I starto the application, I put break in several points and at the moment that the app goes up, on the OnRegistered application to and there I get the token generated. Once I unregistered and registered and generated a new message and it was with the previous token and not the new generated, then when I triggered the notification, I gave the firebase error of: / p>

  

Message status: failed

I placed the valid token, gave the message Sent and in the App I can not get it. Something is blocking the receipt and I do not know what it is. I am suspicious of Security Master , Vysor, My KNOX and etc or Firebase itself, but I'm not sure. Here's the code I've done now, which reported it all: Startup class

[Application]
    public class PushNotificationAppStater : Application
    {
        public static Context AppContext;

        public PushNotificationAppStater(IntPtr javaReference, JniHandleOwnership transfer) 
            : base(javaReference, transfer)
        {

        }

        public override void OnCreate()
        {
            base.OnCreate();

            AppContext = this.ApplicationContext;

            //TODO: Initialize CrossPushNotification Plugin
            //TODO: Replace string parameter with your Android SENDER ID
            //TODO: Specify the listener class implementing IPushNotificationListener interface in the Initialize generic
            CrossPushNotification.Initialize<CrossPushNotificationListener>("806431458293");

            StartPushService();
        }

        public static void StartPushService()
        {
            AppContext.StartService(new Intent(AppContext, typeof(PushNotificationService)));

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
            {

                PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(PushNotificationService)), 0);
                AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
                alarm.Cancel(pintent);
            }
        }

        public static void StopPushService()
        {
            AppContext.StopService(new Intent(AppContext, typeof(PushNotificationService)));
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
            {
                PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(PushNotificationService)), 0);
                AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService);
                alarm.Cancel(pintent);
            }
        }
    }

Message listener class and status

public class CrossPushNotificationListener : IPushNotificationListener
    {
        public void OnError(string message, DeviceType deviceType)
        {

        }

        public void OnMessage(JObject values, DeviceType deviceType)
        {

        }

        public void OnRegistered(string token, DeviceType deviceType)
        {

        }

        public void OnUnregistered(DeviceType deviceType)
        {

        }

        public bool ShouldShowNotification()
        {
            return true;
        }
    }

MainActivity

[Activity(Label = "App1", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        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());
        }
    }

My App.xaml.cs public partial class App: Application     {     public App ()     {         InitializeComponent ();

    MainPage = new App1.MainPage();
}

protected override void OnStart()
{
    CrossPushNotification.Current.Unregister();
    CrossPushNotification.Current.Register();
}

protected override void OnSleep()
{
    // Handle when your app sleeps
}

protected override void OnResume()
{
    // Handle when your app resumes
}

}

My android.manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.global.app.br" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="15" />
    <application android:label="App1.Android" android:icon="@drawable/icon">
    <service
        android:name=".Messaging.FirebaseIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
  </application>
</manifest>

The rest has google-services.json with build option for google-services.json and the installed package is: Xam.Plugin.PushNotification NewtonSoft.json

These were the only plugins I installed. What could be the problem?

    
asked by anonymous 27.09.2017 / 20:42

1 answer

3
  

NOTE: FOOTSTEPS FOR CONFIGURING XAMARIN FORMS, THINKING OF ANDROID SETTINGS. FOR IOS, I CAN MAKE A STEP BY STEP AFTER.

Come on, I'll shape the answer to the topic. The whole process is simple, but it gets hard to figure out because too much in the documentation is "makes it work."

So let's go.

  

Preparing the project.

First thing you need to do is update the SDK and configure it in the Project Properties, to point to the correct API. I will show in my project (Xamarin.Forms) as it is, in the images below. Most Important: Add internet permission for the application.

Oncethisisdone,weneedtoupdatethenugetfiles.Thesecrethereistogiveabuildintheprojectafterchangingthesettingsabove,closeVisualStudioandopenitagain,todetectthechanges(theoldoneleavesthefuscaandenterthefusca).

Updateeverythingthatappears,andthenwe'lladdtworeferences:theXamarin.GooglePlayServices.BaseandtheXamarin.Firebase.Messaging.Theothersareautomaticallyaddedasdependencies.

Oncethisisdone,let'sstartwiththecode.

  

Codeimplementation.

I'llassumeyou'vealreadycreatedaprojectinFirebase,addedtheapplicationtoit.Ifyoudidnot,youcanseethestepbystep here .

First thing we have to hit, the project manifest. I'll put my manifest here

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" package="br.com.grupoestudos.app1xamarin" android:versionCode="1" android:versionName="1">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="25" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="App1.Android" android:icon="@drawable/Icon">

    <receiver
    android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
    android:exported="false" />

    <receiver
        android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="${applicationId}" />
      </intent-filter>
    </receiver>

  </application>
</manifest>

Explaining what happens underneath the cloths. The xamarin will register two IntentReceivers to listen to firebase events. Because the firebase sends messages to Google Play Services, it replicates the message to the applications. In this case, only the current application will receive a message sent by the firebase, to the applicationId. This value does not need to change as it automatically takes the google-services.json file.

Speaking of the file, the second step is to get the google-services.json file that is downloaded after configuring the app in Firebase, and put it in the root of the android project. Then open the app properties and change the Build Action to GoogleServicesJson. This option will only appear (if it does not appear from the press), after installing Xamarin.Firebase.Messaging and closing and opening Visual Studio again (it's horribly annoying to have to do this, and I do not even know why I need to do it). >

Third.Let'screateaclass,whichimplementsFirebaseInstanceIdService.Theappwillcallthisclassbyitself,inordertoregistertheappintheFirebaseproject.Itdoesthisautomaticallybyreadingandregisteringtheappunderneaththecloths.

usingAndroid.App;usingAndroid.Content;usingFirebase.Iid;usingAndroid.Util;usingFirebase.Messaging;namespaceApp1.Droid.Firebase{[Service][IntentFilter(new[]{"com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseIIDService : FirebaseInstanceIdService
    {
        const string TAG = "MyFirebaseIIDService";
        public override void OnTokenRefresh()
        {
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Log.Debug(TAG, "Refreshed token: " + refreshedToken);
            SendRegistrationToServer(refreshedToken);
        }
        void SendRegistrationToServer(string token)
        {
            //Neste método, é possível enviar o token para um servidor ou api, atualizando o token do dispositivo.
        }
    }
}

29.09.2017 / 15:50