Xamarin L oop (поток) в службе переднего плана не продолжается, когда устройство отключено - PullRequest
0 голосов
/ 18 июня 2020

Привет, у меня проблема с получением местоположения каждые 1-5 минут с помощью службы переднего плана, когда я отключаю устройство и выключаю экран, поток останавливается, но уведомление службы отображается все время, как я могу предотвратить это?

Я читал об использовании AlarmManager (это реальное решение), как я могу это сделать? или только служба переднего плана должна делать это самостоятельно

это мой код:

using Android.App;
using Android.Content;
using Android.Locations;
using Android.OS;
using Android.Text.Format;
using Invima.VehiculosApp.ViewModels;
using Java.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace Invima.VehiculosApp
{
    [Service(Label = "LocationUpdatesService", Enabled = true, Exported = true)]
    [IntentFilter(new string[] { "com.Antss.InvimaVehiculos.Service" })]
    public class LocationService : Service
    {
        IBinder Binder;
        public override IBinder OnBind(Intent intent)
        {
            return Binder;
        }

        public const int ServiceRunningNotifID = 9000;

        Ruta ruta;
        Thread hiloUbicacion;

        private System.Timers.Timer timer;

        public override void OnCreate()
        {
            Notification notif = DependencyService.Get<INotification>().ReturnNotif();
            StartForeground(ServiceRunningNotifID, notif);

            _ = TomarUbicaciones();

            base.OnCreate();
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            string rutaStr = intent.GetStringExtra("ruta");

            this.ruta = JsonConvert.DeserializeObject<Ruta>(rutaStr);

            var autoEvent = new AutoResetEvent(false);

            // i tried this but ... the same problem
            timer = new System.Timers.Timer(30000);
            timer.Elapsed += async (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                using (HttpClient cl = new HttpClient())
                {
                    await cl.GetAsync("https://webhook.site/a718fef4-769b-4871-87a8-ec1ccd83fc50");
                }
            };
            timer.Start();

            return StartCommandResult.Sticky;
        }


        public int TomarUbicaciones()
        {
            hiloUbicacion = new Thread(TomarUbicacionAsync);
            hiloUbicacion.Start();
            return 1;
        }

        int contador = 0;
        public async void TomarUbicacionAsync()
        {

            while (true)
            {
                try
                {
                    var request = new GeolocationRequest(GeolocationAccuracy.Medium);
                    var location = await Geolocation.GetLocationAsync(request);


                    if (location != null && ruta != null)
                    {

                        Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");

                        App.BD.RutaUbicacion.Add(new RutaUbicacion
                        {
                            Fecha = DateTime.Now,
                            IdRuta = ruta.IdRuta,
                            Latitud = (decimal)location.Latitude,
                            Longitud = (decimal)location.Longitude,
                            Altitud = (decimal)location.Altitude
                        });

                        App.BD.SaveChanges();

                        App.Sincronizar();
                    }


                    Device.BeginInvokeOnMainThread(() =>
                    {
                        DependencyService.Get<IMessage>().ShortAlert("Done!");
                    });
                }
                catch (Exception ex)
                {
                }


                Thread.Sleep(60000);  // each minute
            }
        }

        public override void OnDestroy()
        {
            try
            {
                hiloUbicacion.Abort();
            }
            catch { }
            base.OnDestroy();
        }

        public override bool StopService(Intent name)
        {
            try
            {
                hiloUbicacion.Abort();
            }
            catch { }
            return base.StopService(name);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...