我正在尝试为安卓应用程序在毛伊岛创建前台服务(使用.NET 6),但目前还没有关于实现这一目标的教程(我可以找到)。
添加前台服务的最佳起点是什么,或者如何创建它?
发布于 2022-09-26 03:51:01
您可以创建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;
    }
}
}在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"/>发布于 2022-09-23 15:53:19
首先,您需要了解MAUI --它是多平台的,因此您需要知道,您需要配置运行前台服务的每个特定平台。
了解到您可以开始在这的microsoft中阅读Xamarin,并修改dotnet中的那些文档(通常,如果我们在毛伊岛找不到信息,我们会检查xamarin文档,如果有人遇到类似的问题,我们会在github maui问题上查看)。
此外,在这个链接中是一个例子,说明了如何在android上使用毛伊岛(西班牙语)实现前台服务。
https://stackoverflow.com/questions/73829758
复制相似问题