Background Service in Xamarin Forms

I have a background service in android is implemented as :

         [Service]
        public class PeriodicService : Service
        {
            public override IBinder OnBind(Intent intent)
            {
                return null;
            }

            public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
            {
                base.OnStartCommand(intent, flags, startId);

                // From shared code or in your PCL]
                Task.Run(() => {
                    MessagingCenter.Send<string>(this.Class.Name, "SendNoti");
                });

                return StartCommandResult.Sticky;
            }

        }

In MainActivity Class :

        public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
        {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            UserDialogs.Init(() => (Activity)Forms.Context);
            LoadApplication(new App());

            StartService(new Intent(this, typeof(PeriodicService)));
        }
    }

In Xamarin Forms in My login page :

     public LoginPage()
        {
            InitializeComponent();

            int i = 0;
            MessagingCenter.Subscribe<string>(this, "SendNoti", (e) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    i++;

                    CrossLocalNotifications.Current.Show("Some Text", "This is notification!");                        

                    }
                });
            });

        }

The main problem here is my Periodic service is not sending any message except for the first time. The notification is shown only once! Please help.

Answers

  • You have to set a different notification id for each notification you need to send. otherwise, the notification will be updated only.
    for example use this snippet
    Notification n = new Notification ();
    n .Title = "Some Text";
    n.Message = "This is notification!"
    n.id = 10;
    CrossLocalNotifications.Current.Show(n);

    n = new Notification ();
    n .Title = "Some Text 2";
    n.Message = "This is notification 2!"
    n.id = 11;
    CrossLocalNotifications.Current.Show(n);

    instead of
    CrossLocalNotifications.Current.Show("Some Text", "This is notification!");

Sign In or Register to comment.