10

I am having a difficult time finding documentation on background tasks support for Xamarin.Forms. Does Xamarin.Forms provide support for periodic background tasks?

I need to implement this for both Windows Phone 10 and Android.

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118

3 Answers3

19

XF has no implementation for background tasks. You will need to implement these natively. Below are examples on how to do it for each type of project.

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

Just for those that want iOS as well. https://developer.xamarin.com/guides/ios/application_fundamentals/backgrounding/part_3_ios_backgrounding_techniques/

Xamarin.Forms

Going into more detail for each section is https://xamarinhelp.com/xamarin-background-tasks/

Adam
  • 16,089
  • 6
  • 66
  • 109
-5

Yeas, but it depends what you need to do.

You can for example use System.Threading.Timer (.net class) is Activity/Service

private System.Threading.Timer timer;

In Activity OnCreate

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

In Activity OnDestroy

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
}
Majkl
  • 765
  • 1
  • 9
  • 25
  • Thanks. But I actually want to run a task in the background when my app isn't loaded. – Scott Nimrod Jan 21 '16 at 12:23
  • So you can either use your own auxiliary service in background, which will run continuously and will "managed" the main application. or some "scheduler" http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android – Majkl Jan 21 '16 at 12:27
-5

I use Xamarin.Forms.Device.StartTimer Method, it starts a recurring timer using the device clock capabilities. While the callback returns true, the timer will keep recurring.

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

NPV
  • 41
  • 4