Search code examples
c#maui

how to request periodically the location in a Foreground Service in an Android application developped with MAUI?


I want to create a forground service. This foreground service has to retrive the location every 5 minutes.

To create and start the foreground service, I have followed the code in the answer in this question: How to create an Android foreground service in MAUI

However, it only shows the notificaction in the status bar, but it doesn't anything more.

I have two questions.

First: in the example, I have to click a button to start the service. But if I want to start the foreground when the application starts, Should I start the service in the MauiProgram.cs file? or perhaps in the code behind of the main page?

Second: the foreground service only shows an icon in the status bar, but I need to retrive periodically the location. For that, I was thinking to use a BackgroundWorker, but this is a .NET resource, from System.ComponentModel. I don't know if I can use it in the foreground service, because it belongs to the Android platform. If it is not possible to use it, how could I retrieve the location periodically?

Thanks.

How should I do the next? create


Solution

  • In the read.me of this repository it explains about the permanent foreground services that run from time to time.

    In short, a service that launches notifications from time to time forever (even when you restart the device). Use a timer for the function that runs periodically.

    Now instead of launching notifications you must have a method that obtains the location so that it is invoked in the timer. For this you can use the Location class of Microsoft.Maui.Devices.Sensors.

    But in order to obtain the location in the background, you will not only have to declare permissions in the Manifest, but you will also have to show a dialog to the user so that they accept the location forever (The users themselves must accept the permissions), doing this with the Android libraries is very complicated, this can be achieved more easily with the Permissions class of Microsoft.Maui.ApplicationModel.

    There are many concepts that come into play. I recommend you follow this route

    1 - Periodic ForegroundServices https://github.com/carlfranklin/MAUIAndroidFS/tree/master

    2- Here a geolocator service is programmed in Native Android. I recommend it more than anything to understand the necessary permissions and declarations in the Manifest. https://www.youtube.com/watch?v=YZL-_XJSClc

    I hope it at least serves as a guide for you.

    EDIT: You also have to use wakelock to keep your service running