'Xamarin Forms Background Service not working

I created a service to run in the background.

The service looks like this

[Service]
    public class LocationServices : Service
    {
        Timer timer = new Timer();
        public static Intent Instance;
        internal static readonly string CHANNEL_ID = "my_notification_channel";
        internal static readonly int NOTIFICATION_ID = 100;
        public override IBinder OnBind(Intent intent)
        {
            return null;
        }
        /*
         * This service will run until stopped explicitly because we are returning sticky
         */
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            //Toast.MakeText(this, "Service started", ToastLength.Long).Show();
            StartServiceInForeground();
            return StartCommandResult.Sticky;
        }
        /*
         * When our service is to be destroyed, show a Toast message before the destruction.
         */
        public override void OnDestroy()
        {
            base.OnDestroy();
            //Toast.MakeText(this, "Syncing stopped", ToastLength.Long).Show();
        }

        void StartServiceInForeground()
        {

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var intent = new Intent(this, typeof(MainActivity));
                
                var channel = new NotificationChannel(CHANNEL_ID, "Service Channel", NotificationImportance.High)
                {
                    Description = "Foreground Service Channel"
                };

                var notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.CreateNotificationChannel(channel);
                var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.Immutable);
                var notification = new Notification.Builder(this, CHANNEL_ID)
                .SetContentTitle("VizzWasher")
                .SetContentText("Vizz lokasiyanı qeyd edir.")
                //.SetContentIntent(pendingIntent)
                .SetSmallIcon(Resource.Mipmap.launcher_foreground)
                .SetOngoing(true)
                .Build();
                StartForeground(NOTIFICATION_ID, notification);
            }
            
            
            timer.Interval = 500;
            timer.Elapsed += ProcessMethod;
            timer.Start();

        }
        async void ProcessMethod(object sender, ElapsedEventArgs e) //object sender, ElapsedEventArgs e
        {
            await Task.Run(() => Method());
        }
        static float x = float.Parse("49.655562");
        static float y = float.Parse("49.655562");
        async void Method()
        {
            try
            {

                var status = await CrossPermissions.Current.CheckPermissionStatusAsync<LocationWhenInUsePermission>();
                if (Device.RuntimePlatform == Device.iOS && status == Plugin.Permissions.Abstractions.PermissionStatus.Denied)
                {

                }
                if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
                    {
                        //Gunna need that location
                    }
                    var b = CrossPermissions.IsSupported;
                    status = await CrossPermissions.Current.RequestPermissionAsync<Plugin.Permissions.LocationWhenInUsePermission>();
                    Xamarin.Forms.Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings));
                    return;
                }


                if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    
                    try
                    {
                        var request = new GeolocationRequest(GeolocationAccuracy.Medium);
                        var loc = await Geolocation.GetLocationAsync(request);
                        VizzWasher.Model.Location location = new VizzWasher.Model.Location();
                        location.WasherUserId = Program.userId;
                        location.x = float.Parse(loc.Latitude.ToString());
                        location.y = float.Parse(loc.Longitude.ToString());
                        CallFromApi.ChangeLoc(location);
                        
                    }
                    catch(FeatureNotEnabledException ee)
                    {
                        timer.Stop();
                        try
                        {
                            VizzWasher.Utils.CallFromApi api = new VizzWasher.Utils.CallFromApi();
                            string rslt1 = api.LoginAPI(new Model.LoginUserInfo() { email = Program.username, password = Program.password });
                            ResponseDto dto1 = JsonSerializer.Deserialize<ResponseDto>(rslt1);
                            if (dto1.statusCode == 200)
                            {
                                WasherUsers user = JsonSerializer.Deserialize<WasherUsers>(dto1.obj.ToString());
                                user.passHash = Program.password;
                                user.status = 1;
                                api.UpdateAPI(user);
                                string rslt2 = api.LoginAPI(new Model.LoginUserInfo() { email = Program.username, password = Program.password });
                                ResponseDto dto2 = JsonSerializer.Deserialize<ResponseDto>(rslt2);
                                Program.obj = (JsonElement)dto2.obj;

                                var intent = new Intent(this, typeof(MainActivity));
                                var channel = new NotificationChannel(CHANNEL_ID, "Service Channel", NotificationImportance.High)
                                {
                                    Description = "Foreground Service Channel"
                                };
                                var notificationManager = (NotificationManager)GetSystemService(NotificationService);
                                notificationManager.CreateNotificationChannel(channel);
                                var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.Immutable);
                                var notification = new Notification.Builder(this, CHANNEL_ID)
                                .SetContentTitle("Vizz lokasiyanı qeyd edə bilmədi.")
                                .SetContentText("Məkanı aktiv edin.")
                                .SetContentIntent(pendingIntent)
                                .SetSmallIcon(Resource.Mipmap.launcher_foreground)
                                .SetOngoing(true)
                                .Build();
                                StartForeground(NOTIFICATION_ID, notification);


                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        MainActivity.Instance.Finish();
                    }
                    catch (WebException e)
                    {
                        if(e.Message == "Unable to read data from the transport connection: Connection reset by peer.")
                        {

                        }
                        else
                        {
                            //timer.Stop();
                            //MainActivity.Instance.Finish();
                        }
                        
                    }
                    catch (Exception ee)
                    {
                        
                    }
                }
            }
            catch (Exception ex)
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync<LocationWhenInUsePermission>();
                if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
                    {
                        //Gunna need that location
                    }
                    //Permissions.ShouldShowRationale<Permissions.LocationWhenInUse>();
                    //await Permissions.RequestAsync<Xamarin.Essentials.Permissions.LocationWhenInUse>();
                    var b = CrossPermissions.IsSupported;
                    status = await CrossPermissions.Current.RequestPermissionAsync<Plugin.Permissions.LocationWhenInUsePermission>();
                    Xamarin.Forms.Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings));
                    return;
                }
            }
        }
    }

The problem is that this service works perfectly when the application is open. But when I close the application, the service does not work. The service does not stop itself and does not throw an error.

Service is active but not working in the background, how can I do this?

EDIT

I test app on API 27. It work great. But background service is undefined on API 30



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source