首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在毛伊岛创建Android前台服务

如何在毛伊岛创建Android前台服务
EN

Stack Overflow用户
提问于 2022-09-23 15:08:07
回答 2查看 638关注 0票数 1

我正在尝试为安卓应用程序在毛伊岛创建前台服务(使用.NET 6),但目前还没有关于实现这一目标的教程(我可以找到)。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-26 03:51:01

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

我已经做了一个样本并成功地开始了,你可以试一试。

在\Platform\Android\ForegroundServiceDemo中:

代码语言:javascript
运行
复制
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中:

代码语言:javascript
运行
复制
 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中:

代码语言:javascript
运行
复制
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
票数 5
EN

Stack Overflow用户

发布于 2022-09-23 15:53:19

首先,您需要了解MAUI --它是多平台的,因此您需要知道,您需要配置运行前台服务的每个特定平台。

了解到您可以开始在的microsoft中阅读Xamarin,并修改dotnet中的那些文档(通常,如果我们在毛伊岛找不到信息,我们会检查xamarin文档,如果有人遇到类似的问题,我们会在github maui问题上查看)。

此外,在这个链接中是一个例子,说明了如何在android上使用毛伊岛(西班牙语)实现前台服务。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73829758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档