Search code examples
androidmauiforeground-service.net-maui

How to create an Android foreground service in MAUI


I'm trying to create a foreground service in MAUI (using .NET 6) for an Android app, but currently, there are no tutorials (that I could find) on achieving this.

What would be the best starting point to add a foreground service or how would you create it?


Solution

  • You can create the ForegroundService \Platform\Android and then start it in the page.cs.

    I have done a sample and start it successfully, you can have a try.

    In the \Platform\Android\ForegroundServiceDemo:

    namespace MauiAppTest.Platform.Android
    {
    [Service]
    public class ForegroundServiceDemo : Service
    {
        private string NOTIFICATION_CHANNEL_ID = "1000";
        private int NOTIFICATION_ID = 1;
        private string NOTIFICATION_CHANNEL_NAME = "notification";
    
        private void startForegroundService()
        {
            var notifcationManager = GetSystemService(Context.NotificationService) as NotificationManager;
    
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                createNotificationChannel(notifcationManager);
            }
    
            var notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
            notification.SetAutoCancel(false);
            notification.SetOngoing(true);
            notification.SetSmallIcon(Resource.Mipmap.appicon);
            notification.SetContentTitle("ForegroundService");
            notification.SetContentText("Foreground Service is running");
            StartForeground(NOTIFICATION_ID, notification.Build());
        }
    
        private void createNotificationChannel(NotificationManager notificationMnaManager)
        {
            var channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME,
            NotificationImportance.Low);
            notificationMnaManager.CreateNotificationChannel(channel);
        }
    
        public override IBinder OnBind(Intent intent)
        {
            return null;
        }
    
    
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            startForegroundService();
            return StartCommandResult.NotSticky;
        }
    }
    }
    

    And in the page.cs:

     private void OnStartServiceClicked(object sender, EventArgs e)
    {
    #if ANDROID
        Android.Content.Intent intent = new Android.Content.Intent(Android.App.Application.Context,typeof(ForegroundServiceDemo));
        Android.App.Application.Context.StartForegroundService(intent);
    #endif
    }
    

    Finally, add the foreground service permission into the AndroidManifest.xml:

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>