Does Xamarin.Forms support periodic background tasks? - xamarin

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.

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/

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
}

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/

Related

How to implement a service which run on every x second in xamarin ios

I want to implement a service which check my device is connected to TCP or not at every some seconds in Xamarin iOS, I want to implement these in native code.
In Xamarin.iOS you could use NSTimer
NSTimer _timer;
_timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), (timer) =>
{
this.InvokeOnMainThread(() =>
{
//Your code here
});
}
);
To Start the Timer
_timer.Fire();
To End The Timer
_timer.Invalidate();

ViewChanged suppress on Windows Phone 8.1

There is a way to fire the event ViewChanged (that was present in previous WP8) within an Windows Phone 8.1 app? I use Windows.UI.Xaml.Controls.Maps and I will manage the map when the view animation finishes.
You can try to use on of these events of the MapControl class:
ManipulationStarted: http://msdn.microsoft.com/en-us/library/hh702372.aspx
CenterChanged: http://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.maps.mapcontrol.centerchanged.aspx
ZoomLevelChanged: http://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.maps.mapcontrol.zoomlevelchanged.aspx
But the best event would be ManipulationCompleted: http://msdn.microsoft.com/en-us/library/windows.ui.xaml.uielement.manipulationcompleted.aspx
I've found that the LoadingStatusChanged event does what you want, provided you check the LoadingStatus first.
mapControl.LoadingStatusChanged += MapLoadingStatusChanged;
private void MapLoadingStatusChanged(MapControl sender, object args)
{
if (sender.LoadingStatus == MapLoadingStatus.Loaded)
{
// code here will only get hit when the map finishes drawing after a pan/zoom
}
}

MediaPlayer.Play() causes UI to freeze

Everytime MediaPlayer.Play() is executed from the UI thread the UI freezes for a significant amount of time. I don't think you can do anything about the time it takes to start playing the SongCollection but at least the UI should stay responsive.
Running MediaPlayer.Play() from another thread obviously doesn't work.
The MediaPlayer is a component from the Xna Namespace. If you are using this feature in a game, you are most certain running a GameLoop to prevent this freeze from happening: GameLoop
If you use this component in an App, you can simulate this behavior your own
public MainPage()
{ InitializeComponent();
// Timer to simulate the XNA Game Studio game loop (Microphone is from XNA Game Studio)
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(33);
dt.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
dt.Start();
}
(see complete sample on how to run a microphone outside a gameloop: msdn)

Windows Phone Toast notification not firing at specified time

I am creating an app with a timer in it. I want to display a toast notification(or some sort of notification) if the person leaves the app so they know the timer is over. I used the "PeriodicTask" using ".FromSeconds", but it seemed it didn't fire it at the specified time.
PeriodicTask periodicTask = new PeriodicTask("TaskTest");
periodicTask.Description = "Task";
try
{
IsolatedStorageSettings.ApplicationSettings["TimerForSchedule"] = TimeNum;
ScheduledActionService.Add(periodicTask);
ScheduledActionService.LaunchForTest("TaskTest", TimeSpan.FromSeconds(((TimeNum*60))));
}
On the "OnInvoke" method for the scheduled agent project, I have the following:
protected override void OnInvoke(ScheduledTask task)
{
if (task.Name == "TaskTest")
{
int time = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["TimerForSchedule"]);
bool periodic = (bool)(task is PeriodicTask);
ShellToast toast = new ShellToast();
toast.Title = "Done";
toast.Content = "Timer is over";
toast.Show();
}
NotifyComplete();
ScheduledActionService.Remove("TaskTest");
}
Everything seems to fire properly because I DO get a notification, but I do not get it at the expected time.
Any help would be appreciated.
Is your app running in the foreground? If so, the ShellToast won't show up. Your app must be in the background for it to show up. Read more about that and potential workaround at my other # How can I create a shelltoast?
I think that the time you set to run your PeriodicTask is just a hint for the OS, it does not mean that it will fire it exactly at that time.

Easy way to excecute method after a given delay?

Is there a easy way to perform a method after a given delay like in iOS out of the box?
On iPhone I would do this:
[self performSelector:#selector(connectSensor) withObject:nil afterDelay:2.5];
It will then schedule the method connectSensor on the main thread (UI thread) to be executed after 2,5 seconds. And because it is automatically scheduled on the main thread, you don't have to worry about cross thread issues. (There is also a performSelectorOnBackground version)
So how would I do this properly in WP7?
Currently I'm accomplishing this with a timer, but I'm not sure if this is a good solution.
private Timer timer;
private void DoSomethingAfterDaly()
{
// ... do something here
timer = new Timer( (o) => Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.GoBack()), null, 2500, Timeout.Infinite);
}
How could this be encapsulated into an extension method so I can just call this.Perform(MyMethod, null, 2500); ?
You can use a BackgroundWorker like so:
private void Perform(Action myMethod, int delayInMilliseconds)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) => Thread.Sleep(delayInMilliseconds);
worker.RunWorkerCompleted += (s, e) => myMethod.Invoke();
worker.RunWorkerAsync();
}
The call into this method would look like this:
this.Perform(() => MyMethod(), 2500);
The background worker will run the sleep on a thread off of the UI thread so your application is free to do other things while the delay is occurring.
You can use the Reactive Extensions for WP7 to observe on a timer:
Observable
.Timer(TimeSpan.FromMilliseconds(2500))
.SubscribeOnDispatcher()
.Subscribe(_ =>
{
NavigationService.GoBack();
});
Given the brevity of this code, I don't think you'd gain much by creating an extension method for it :) For more information about the Reactive Extensions for WP7, take a look at this MSDN page
.

Resources