Skip to main content

BackGround Service Get Location Xamrin Forms


1) PCL:

using System;

using Xamarin.Forms;

namespace myapp
{
    public class LongRunningPage : ContentPage
    {
        Label lbl;
        public LongRunningPage()
        {
            Button startbtn = new Button();
            startbtn.Text = "Start";

            Button stopbtn = new Button();
            stopbtn.Text = "Stop";

            lbl = new Label();
            lbl.Text = "";

            Content = new StackLayout
            {
                Spacing=20,
                Children = {
                    startbtn,stopbtn,lbl
                }
            };
            startbtn.Clicked += (s, e) => {
                var message = new StartLongRunningTaskMessage();
                MessagingCenter.Send(message, "StartLongRunningTaskMessage");
            };
            stopbtn.Clicked += (s, e) => {
                var message = new StopLongRunningTaskMessage ();
                MessagingCenter.Send (message, "StopLongRunningTaskMessage");
            };
               



            HandleReceivedMessages();
        }
        void HandleReceivedMessages()
        {
            MessagingCenter.Subscribe<TickedMessage>(this, "TickedMessage", message => {
                Device.BeginInvokeOnMainThread(() => {
                    lbl.Text = message.lat.ToString() + "\n" + message.lon.ToString();
                });
            });

            MessagingCenter.Subscribe<CancelledMessage>(this, "CancelledMessage", message => {
                Device.BeginInvokeOnMainThread(() => {
                    lbl.Text = "Cancelled";
                });
            });
        }
    }
}

2)Methods:
public class StartLongRunningTaskMessage
    {
       
    }
 public class StopLongRunningTaskMessage
    {
       
    }
 public class CancelledMessage
    {
      
    }

public class TickedMessage
    {
        public string Message { get; set; }

        public string lat { get; set; }

        public string lon { get; set; }
    }

using Plugin.Geolocator;
 public class TaskCounter
    {
        public async Task RunCounter(CancellationToken token)
        {
            await Task.Run(async () => {

                for (long i = 0; i < long.MaxValue; i++)
                {
                    token.ThrowIfCancellationRequested();

                    await Task.Delay(2000);

                    var locator = CrossGeolocator.Current;
                    locator.DesiredAccuracy = 50;
                    var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1));
                    var lat = position.Latitude;
                    var longt = position.Longitude;
                    var message = new TickedMessage
                    {
                        Message = i.ToString(),
                        lat = lat.ToString(),
                        lon = longt.ToString()


                    };

                    Device.BeginInvokeOnMainThread(() => {
                        DependencyService.Get<IMessage>().ShortAlert(message.lat + message.lon);
                        MessagingCenter.Send<TickedMessage>(message, "TickedMessage");
                    });
                }
            }, token);
        }
    }

3)Android:

i)service
using Android.App;
using Android.Content;
using System.Threading.Tasks;
using Android.OS;
using System.Threading;
using Xamarin.Forms;
using Orbishealth_patient.Test;
namespace myapp
{
    [Service]
    public class LongRunningTaskService : Service
    {
        CancellationTokenSource _cts;

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            _cts = new CancellationTokenSource();

            Task.Run(() => {
                try
                {
                    //INVOKE THE SHARED CODE
                    var counter = new TaskCounter();
                    counter.RunCounter(_cts.Token).Wait();
                }
                catch (OperationCanceledException)
                {
                }
                finally
                {
                    if (_cts.IsCancellationRequested)
                    {
                        var message = new CancelledMessage();
                        Device.BeginInvokeOnMainThread(
                            () => MessagingCenter.Send(message, "CancelledMessage")
                        );
                    }
                }

            }, _cts.Token);

            return StartCommandResult.Sticky;
        }

        public override void OnDestroy()
        {
            if (_cts != null)
            {
                _cts.Token.ThrowIfCancellationRequested();

                _cts.Cancel();
            }
            base.OnDestroy();
        }
    }
}


ii)mainactivity:

using System;

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Messier16.Forms.Android.Controls;
using Plugin.Permissions;
using Xamarin.Forms;
using myapp;


namespace 
myapp.Droid
{
    [Activity(Label = "Orbishealth_patient.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
           

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

           
            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
           
            LoadApplication(new App());
            WireUpLongRunningTask();
        }
        void WireUpLongRunningTask()
        {
            MessagingCenter.Subscribe<StartLongRunningTaskMessage>(this, "StartLongRunningTaskMessage", message => {
                var intent = new Intent(this, typeof(LongRunningTaskService));
                StartService(intent);
            });

            MessagingCenter.Subscribe<StopLongRunningTaskMessage>(this, "StopLongRunningTaskMessage", message => {
                var intent = new Intent(this, typeof(LongRunningTaskService));
                StopService(intent);
            });
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}




Comments

  1. Nice post. I was checking continuously this blog and I’m
    impressed! Extremely useful info specially the last part
    I care for such info much. I was looking for this particular info for a very long time.

    Thank you and good luck.

    Hire Xamarin Developer
    Hire Xamarin Mobile app Developer

    ReplyDelete
  2. Outstanding work author. Knowledgeable enough. We will surely share your work. Anyway, If you are interested and looking for website development you may visit this website
    web and app development company
    hire xamarin developer
    hire abp.io developer
    hire .net developer

    ReplyDelete

Post a Comment

Popular posts from this blog