Skip to content Skip to sidebar Skip to footer

How To Create A Xamarin Foreground Service

Trying to create my first Xamarin foreground service but can't find a suitable example. The examples in Microsoft documentation seem to be either incomplete or use depreciated Noti

Solution 1:

I have finally stitched together an answer. Here is an example for anyone who find themselves here:

Create a Dependency Service so you can call your Start/Stop service methods from your shared code.

Make Interface:

publicinterfaceIAndroidService
    {
        voidStartService();

        voidStopService();
    }

Implement a class within your android project which uses the interface. Remember to add assembly reference.

[assembly: Xamarin.Forms.Dependency(typeof(AndroidServiceHelper))]

namespace YourNameSpace.Droid
{
    internal classAndroidServiceHelper : IAndroidService
    {
        privatestaticContextcontext= global::Android.App.Application.Context;

        publicvoidStartService()
        {
            varintent=newIntent(context, typeof(DataSource));

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                context.StartForegroundService(intent);
            }
            else
            {
                context.StartService(intent);
            }
        }

        publicvoidStopService()
        {
            varintent=newIntent(context, typeof(DataSource));
            context.StopService(intent);
        }
    }
}

Now we do pretty much the same (create interface and implement in class within android project) for creating the notification needed for a Foreground Service:

The interface for creating notifications

publicinterfaceINotification
    {
        Notification ReturnNotif();
    }

Create a class inside of the android project that implements INotification so we can create and return a notification object which we need to start a Foreground Service. Remember to add the assembly reference:

[assembly: Xamarin.Forms.Dependency(typeof(NotificationHelper))]

namespace MetroAlarmHandlerMobile.Droid
{
    internal classNotificationHelper : INotification
    {
        privatestaticstringforegroundChannelId="9001";
        privatestaticContextcontext= global::Android.App.Application.Context;


        public Notification ReturnNotif()
        {
            // Building intentvarintent=newIntent(context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.SingleTop);
            intent.PutExtra("Title", "Message");

            varpendingIntent= PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);

            varnotifBuilder=newNotificationCompat.Builder(context, foregroundChannelId)
                .SetContentTitle("Your Title")
                .SetContentText("Main Text Body")
                .SetSmallIcon(Resource.Drawable.MetroIcon)
                .SetOngoing(true)
                .SetContentIntent(pendingIntent);

            // Building channel if API verion is 26 or aboveif (global::Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                NotificationChannelnotificationChannel=newNotificationChannel(foregroundChannelId, "Title", NotificationImportance.High);
                notificationChannel.Importance = NotificationImportance.High;
                notificationChannel.EnableLights(true);
                notificationChannel.EnableVibration(true);
                notificationChannel.SetShowBadge(true);
                notificationChannel.SetVibrationPattern(newlong[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                varnotifManager= context.GetSystemService(Context.NotificationService) as NotificationManager;
                if (notifManager != null)
                {
                    notifBuilder.SetChannelId(foregroundChannelId);
                    notifManager.CreateNotificationChannel(notificationChannel);
                }
            }

            return notifBuilder.Build();
        }
}

Create a class that inherits and overrides from Service. This is a class created in your shared code and is where we will call the methods that we want to run on the Foreground Service.

publicclassDataSource : Service
    {

        publicoverride IBinder OnBind(Intent intent)
        {
            returnnull;
        }

        publicconstint ServiceRunningNotifID = 9000;

        publicoverride StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Notification notif = DependencyService.Get<INotification>().ReturnNotif();
            StartForeground(ServiceRunningNotifID, notif);

            _ = DoLongRunningOperationThings();

            return StartCommandResult.Sticky;
        }

        publicoverridevoidOnDestroy()
        {
            base.OnDestroy();
        }

        publicoverrideboolStopService(Intent name)
        {
            returnbase.StopService(name);
        }


}

You can now start and stop your Foreground Service using Dependency Service anywhere in your shared code using the following code:

Start

DependencyService.Get<IAndroidService>().StartService();

Stop

DependencyService.Get<IAndroidService>().StopService();

Solution 2:

The question should probably be, "How should I find examples for uncommon Xamarin Native functionality?"

If you are looking for examples for uncommon functionality, your best friend is GitHub:

  • Just login to GitHub and in the search bar look for the name of the function on all of GitHub, StartForegroundServiceCompat in our case.
  • And voilà, you can now see all the public repos that use that functionality!

Don't forget to write an article and provide an example thats up to date, explaining how it works!

Post a Comment for "How To Create A Xamarin Foreground Service"