如何在MAUI中创建Android前台服务

blu*_*nce 7 android foreground-service maui .net-maui

我正在尝试在 MAUI 中(使用 .NET 6)为 Android 应用程序创建一个前台服务,但目前没有关于实现此目的的教程(我可以找到)。

添加前台服务的最佳起点是什么,或者如何创建它?

Liy*_*SFT 11

您可以创建ForegroundService\Platform\Android,然后在page.cs中启动它。

我已经做了一个示例并启动成功,你可以尝试一下。

在\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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

在 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
}
Run Code Online (Sandbox Code Playgroud)

最后在AndroidManifest.xml中添加前台服务权限:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
Run Code Online (Sandbox Code Playgroud)