首页 > 解决方案 > Xamarin.Android 中的后台服务

问题描述

我正在努力使用 Xamarin.Android 创建后台服务。后台服务应该每 5 分钟运行一次,并且在手机屏幕关闭或应用程序关闭时也应该运行。你知道如何实现这一目标吗?我发现该库运行良好,但问题是间隔未在 15 分钟内运行。我不知道为什么。

https://www.c-sharpcorner.com/article/scheduling-work-with-workmanager-in-android/

我期待着您的支持。谢谢你。

标签: c#androidxamarinxamarin.android

解决方案


我认为BroadcastReceiver将更适合您的任务。它提供了更多的灵活性和设置参数。

声明广播接收器:

using Android.Content;

[BroadcastReceiver]
public class BackgroundBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        // Your code here that will be executed periodically
    }
}

广播接收器注册:

// context - any of your Android activity

var intentAlarm = new Intent(context, typeof(BackgroundBroadcastReceiver));
var alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);

alarmManager.SetRepeating(AlarmType.ElapsedRealtime, // Works even application\phone screen goes off
                          DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), // When to start (right now here)
                          1000, // Receiving interval. Set your value here in milliseconds.
                          PendingIntent.GetBroadcast(context, 1, intentAlarm, PendingIntentFlags.UpdateCurrent));

推荐阅读