我正在努力使用Xamarin.Android创建后台服务。后台服务应该每5分钟工作一次,并且应该在手机屏幕关闭或应用程序关闭时工作。您有任何想法如何实现这一目标。我发现该库正常运行,但问题是间隔在15分钟内无法正常运行。我不知道为什么。
https://www.c-sharpcorner.com/article/scheduling-work-with-workmanager-in-android/
我期待您的支持。谢谢。
using System;
using System;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using OomaAndroid.Models;
using SQLite;
namespace OomaAndroid
{
[Service]
public class ServiceTest : Service
{
Timer timer;
public override void OnCreate()
{
base.OnCreate();
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
timer = new Timer(HandleTimerCallback, 0, 0, 900000);
return base.OnStartCommand(intent, flags, startId);
}
private void HandleTimerCallback(object state)
{
//this part codes will run every 15 minutes
}
}
}
您也可以在MainActivity中运行服务
Intent intSer = new Intent(base.ApplicationContext, typeof(OomaService));
StartService(intSer);
还应该从用户处获得Receive_Boot_Compeleted权限,以在重新启动手机后运行服务
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));