gpt4 book ai didi

xamarin.forms - 每天在 Xamarin Forms 上运行一次任务

转载 作者:行者123 更新时间:2023-12-04 01:31:13 27 4
gpt4 key购买 nike

我几个月前开始使用 xamarin,直到现在,我都不需要做这样的事情。我正在开发一个应用程序,它应该每天运行一次 WCF Web 服务并验证信息是否真实。如果为真,则应在设备上显示通知。我的问题是我不知道如何执行它,我已经阅读了有关后台和计划任务的信息,但我不太了解如何执行此操作。我如何使用 Xamarin.Forms 完成此操作?

谢谢!

最佳答案

对于 Android,一个解决方案需要 4 个组件:

  1. AlarmManager 设置每日检查计划
  2. BroadCastReceiver 接收每日触发器并调用 IntentService
  3. IntentService 执行等待调用
  4. OnBootReceiver 以确保在设备重启后再次设置警报

对于 iOS,您很可能需要远程推送通知。


下面是 Android 组件的一些示例代码:

AlarmManager - 设置闹钟

[assembly: Dependency(typeof(AlarmHelper))] // above the namespace
...
class AlarmHelper: IAlarm
{
var now = Calendar.Instance;
var alarmTime = Calendar.Instance;
alarmTime.Set(CalendarField.HourOfDay, settings.AlarmHour); // Set Alarm start Hour
alarmTime.Set(CalendarField.Minute, settings.AlarmMinutes); // Set Alarm Start Minutes

if (alarmTime.Before(now))
{
alarmTime.Add(CalendarField.Hour, 24);
}

var intent = new Intent(Android.App.Application.Context, typeof(ScheduledAlarmHandler));
var pendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
var alarmManager = Android.App.Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;

alarmManager.SetRepeating(AlarmType.RtcWakeup, alarmTime.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);
}

BroadCastReceiver - 接收警报

[BroadcastReceiver]
class ScheduledAlarmHandler : WakefulBroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Console.WriteLine("ScheduledAlarmHandler", "Starting service @" + SystemClock.ElapsedRealtime());
Intent service = new Intent(context, typeof(WakefulAPIService));
StartWakefulService(context, service);
}
}

IntentService - 执行等待调用

[Service]
[IntentFilter(new String[] { "com.test.testApp.WakefulAPIService" })]
class WakefulAPIService : IntentService
{
protected override void OnHandleIntent(Intent intent)
{
// Your API Call code here

Console.WriteLine("WakefulAPIService", "Completed service @ " + SystemClock.ElapsedRealtime());
Android.Support.V4.Content.WakefulBroadcastReceiver.CompleteWakefulIntent(intent);
}
}

OnBootReceiver - 确保在设备重启后再次设置警报

[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "android.intent.action.BOOT_COMPLETED", "android.intent.action.QUICKBOOT_POWERON" })]
class OnBootReceiver : BroadcastReceiver
{

public override void OnReceive(Context context, Intent intent)
{
Console.WriteLine("On Boot Reveiver", "Alarm Set Again after Reboot");
var alarmHelper = new AlarmHelper();
alarmHelper.SetAlarm();
}

}

此功能所需的权限是“RECEIVE_BOOT_COMPLETED”和“WAKE_LOCK”

关于xamarin.forms - 每天在 Xamarin Forms 上运行一次任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38267152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com