如何创建 Xamarin 前台服务 [英] How to create a Xamarin foreground service

查看:43
本文介绍了如何创建 Xamarin 前台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建我的第一个 Xamarin 前台服务,但找不到合适的示例.Microsoft 文档中的示例似乎不完整或使用了折旧的 Notification.Builder:

Trying to create my first Xamarin foreground service but can't find a suitable example. The examples in Microsoft documentation seem to be either incomplete or use depreciated Notification.Builder:

https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services

https://docs.microsoft.com/en-us/samples/xamarin/monodroid-samples/applicationfundamentals-servicesamples-foregroundservicedemo/

我发现了一个似乎是最新的代码示例,但我正在努力通过查看代码来破译它的工作原理:

I've found ONE code example that seems to be up to date, but I'm struggling to decipher how it works by looking at the code:

https://docs.microsoft.com/en-us/samples/xamarin/monodroid-samples/android-o-androidplaylocation-locupdfgservice/

谁能给我一个如何创建基本前台服务的例子?

Can anyone give me an example of how to create basic foreground service?

推荐答案

我终于拼凑了一个答案.以下是任何发现自己在这里的人的示例:

I have finally stitched together an answer. Here is an example for anyone who find themselves here:

创建一个依赖服务,以便您可以从共享代码中调用启动/停止服务方法.

Create a Dependency Service so you can call your Start/Stop service methods from your shared code.

制作界面:

public interface IAndroidService
    {
        void StartService();

        void StopService();
    }

在您的 android 项目中实现一个使用该接口的类.记得添加程序集引用.

Implement a class within your android project which uses the interface. Remember to add assembly reference.

[assembly: Xamarin.Forms.Dependency(typeof(AndroidServiceHelper))]

namespace YourNameSpace.Droid
{
    internal class AndroidServiceHelper : IAndroidService
    {
        private static Context context = global::Android.App.Application.Context;

        public void StartService()
        {
            var intent = new Intent(context, typeof(DataSource));

            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                context.StartForegroundService(intent);
            }
            else
            {
                context.StartService(intent);
            }
        }

        public void StopService()
        {
            var intent = new Intent(context, typeof(DataSource));
            context.StopService(intent);
        }
    }
}

现在我们做了几乎相同的事情(在android项目中创建接口并在类中实现)来创建前台服务所需的通知:

Now we do pretty much the same (create interface and implement in class within android project) for creating the notification needed for a Foreground Service:

用于创建通知的界面

public interface INotification
    {
        Notification ReturnNotif();
    }

在实现 INotification 的 android 项目中创建一个类,以便我们可以创建并返回一个通知对象,我们需要启动一个前台服务.记得添加程序集引用:

Create a class inside of the android project that implements INotification so we can create and return a notification object which we need to start a Foreground Service. Remember to add the assembly reference:

[assembly: Xamarin.Forms.Dependency(typeof(NotificationHelper))]

namespace MetroAlarmHandlerMobile.Droid
{
    internal class NotificationHelper : INotification
    {
        private static string foregroundChannelId = "9001";
        private static Context context = global::Android.App.Application.Context;


        public Notification ReturnNotif()
        {
            // Building intent
            var intent = new Intent(context, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.SingleTop);
            intent.PutExtra("Title", "Message");

            var pendingIntent = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.UpdateCurrent);

            var notifBuilder = new NotificationCompat.Builder(context, foregroundChannelId)
                .SetContentTitle("Your Title")
                .SetContentText("Main Text Body")
                .SetSmallIcon(Resource.Drawable.MetroIcon)
                .SetOngoing(true)
                .SetContentIntent(pendingIntent);

            // Building channel if API verion is 26 or above
            if (global::Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                NotificationChannel notificationChannel = new NotificationChannel(foregroundChannelId, "Title", NotificationImportance.High);
                notificationChannel.Importance = NotificationImportance.High;
                notificationChannel.EnableLights(true);
                notificationChannel.EnableVibration(true);
                notificationChannel.SetShowBadge(true);
                notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

                var notifManager = context.GetSystemService(Context.NotificationService) as NotificationManager;
                if (notifManager != null)
                {
                    notifBuilder.SetChannelId(foregroundChannelId);
                    notifManager.CreateNotificationChannel(notificationChannel);
                }
            }

            return notifBuilder.Build();
        }
}

创建一个继承并覆盖Service的类.这是在您的共享代码中创建的类,我们将在其中调用要在前台服务上运行的方法.

Create a class that inherits and overrides from Service. This is a class created in your shared code and is where we will call the methods that we want to run on the Foreground Service.

public class DataSource : Service
    {

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        public const int ServiceRunningNotifID = 9000;

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Notification notif = DependencyService.Get<INotification>().ReturnNotif();
            StartForeground(ServiceRunningNotifID, notif);

            _ = DoLongRunningOperationThings();

            return StartCommandResult.Sticky;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

        public override bool StopService(Intent name)
        {
            return base.StopService(name);
        }


}

您现在可以使用以下代码在共享代码中的任何位置使用依赖服务启动和停止前台服务:

You can now start and stop your Foreground Service using Dependency Service anywhere in your shared code using the following code:

开始

DependencyService.Get<IAndroidService>().StartService();

停止

DependencyService.Get<IAndroidService>().StopService();

这篇关于如何创建 Xamarin 前台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆