Xamarin.Forms 是否支持定期后台任务?

Does Xamarin.Forms support periodic background tasks?

我很难找到有关 Xamarin.Forms 后台任务支持的文档。 Xamarin.Forms 是否支持定期后台任务?

我需要为 Windows Phone 10 和 Android 实施此操作。

是的,但这取决于您需要做什么。

你可以例如使用 System.Threading.Timer (.net class) 是 Activity/Service

private System.Threading.Timer timer;

在ActivityOnCreate

TimeSpan timerTime = new TimeSpan(0, 0, 0, 0, 1000);
            timer = new System.Threading.Timer(new System.Threading.TimerCallback(OnTimerFired), null, timerTime, timerTime);

在ActivityOnDestroy

if (timer != null)
            {
                timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                timer.Dispose();
                timer = null;
            }


private void OnTimerFired(object state)
{
    Do some periodic job
}

XF 没有后台任务的实现。您将需要在本机实现这些。以下是有关如何为每种类型的项目执行此操作的示例。

UWP

https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundTask

Android https://developer.xamarin.com/guides/android/application_fundamentals/backgrounding/part_2_android_services/

WinRT

https://visualstudiomagazine.com/articles/2013/05/01/background-tasks-in-windows-store-apps.aspx

iOS

只为那些也想要 iOS 的人。 https://developer.xamarin.com/guides/ios/application_fundamentals/backgrounding/part_3_ios_backgrounding_techniques/

Xamarin.Forms

每个部分的详细信息是 https://xamarinhelp.com/xamarin-background-tasks/

我使用 Xamarin.Forms.Device.StartTimer 方法,它使用设备时钟功能启动循环计时器。当回调 returns 为真时,计时器将继续循环。

http://developer.xamarin.com/api/member/Xamarin.Forms.Device.StartTimer/