Reputation: 2783
In Xamarin Forms, where do I write code that will be run continuously regardless of which page is currently on top of the navigation stack?
I am building an app which must check your location every 10 seconds to see whether you are in a specific location, using the Plugin.Geolocator
nuget package. This code must run at all times, regardless of which page you are currently viewing in the app.
I have already written the code to do this inside a Xaml.cs page code-behind, but where do I write this code so that it runs all the time and performs constant checks every 10 or so seconds?
Upvotes: 2
Views: 83
Reputation: 509
The eassiest sollution would be creating a static method anywhere in your project as long as it's accessible to outside classes and execute the method once in your app.cs in the constructor. The method would go somewhat like this:
public static void CheckPosition(){
Task.Delay(10000).ContinueWith(delegate{
// Your code here
CheckPosition();
});
}
You might get a StackOverflowException after a few runs. I'm not sure though.
Upvotes: 0
Reputation: 2981
You can use Background Tasks to perform this kind of functionality. These do need a platform specific implementation though since they aren't abstracted into Xamarin Forms.
Check this for a quick overview: https://xamarinhelp.com/xamarin-background-tasks/
Upvotes: 2
Reputation: 338
i do not have experience with Xamarin Forms But in Android you have two options: If only will work when app is opened you can use threads and in C# System.Threading Or if you want it to be in Background while app is closed. You will need to use Services but in Xamarin it should be same global idea but different way of implementation i guess
Threads will work inside the app while opened
Services will use Threads but kept working in the Operating system in the background while app is closed but you need to take care with location each 10 min since it will drain battery
Upvotes: 0