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

6
我正在尝试为Android应用程序在MAUI(使用.NET 6)中创建前台服务,但目前没有教程(我找不到)可以实现此目的。如何添加前台服务或如何创建它?请提供最佳起点。
2个回答

10

您可以在 \Platform\Android 创建 ForegroundService,然后在 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;
    }
}
}

同时,在 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
}

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

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

这个带有特定平台子文件夹的提示对我帮助很大! - Portikus
调用StartForeground(NOTIFICATION_ID,myNewNotification.Build());是更新通知文本的正确方式吗? - Kazbek

3
首先你需要了解MAUI是多平台的,所以你需要知道需要配置每个特定的平台来运行前台服务。
了解这一点后,你可以开始阅读Xamarin的Microsoft文档this,并将其适配到.NET MAUI中(通常如果我们在MAUI中找不到信息,我们会检查Xamarin文档和github maui issues以查看是否有类似的问题)。
此外,在这个链接中有一个示例,说明如何使用MAUI在Android上实现前台服务(用西班牙语编写)。

我可以使用相同的方法定期查询REST API并将应用程序带到前台吗,即使它在后台运行? - Vladimir B
想知道在 [Service(ForegroundServiceType = Android.Content.PM.ForegroundService.TypeDataSync)] 中,TypeDataSync 是什么意思?我无法在任何地方找到描述。 - Artur Wyszomirski
感谢提供西班牙语示例的链接。它简单明了,而且代码在GitHub上也有。非常适合入门。 - Álvaro García

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接