我正在尝试为Android应用程序在MAUI(使用.NET 6)中创建前台服务,但目前没有教程(我找不到)可以实现此目的。如何添加前台服务或如何创建它?请提供最佳起点。
您可以在 \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"/>
[Service(ForegroundServiceType = Android.Content.PM.ForegroundService.TypeDataSync)]
中,TypeDataSync 是什么意思?我无法在任何地方找到描述。 - Artur Wyszomirski
StartForeground(NOTIFICATION_ID,myNewNotification.Build());
是更新通知文本的正确方式吗? - Kazbek