Forum Xamarin.Android

Getting gps location data in the background service.

Hi, i am building an app which retrieves location data from the device when its running as background service and when its connected to the server it would send the gps data. The problem is everything is working when the app is open and when i close the app all the process stops working but the app is still running in the background.

I have used source code from this link https://developer.xamarin.com/guides/android/application_fundamentals/backgrounding/part_3_android_backgrounding_walkthrough/

and i have only made some changes in the "LocationService.cs" file.

Tagged:

Answers

  • ParthaSarathyParthaSarathy USMember ✭✭

    Hi I have updated the Attachment, you can try this one, may be it will help you.

  • RizwanZaidiRizwanZaidi USMember

    I have copied your code but the the name 'PerformBackgroundWork' does not exists in the current context.

  • ParthaSarathyParthaSarathy USMember ✭✭

    Hi,
    Sorry forgot to update this below code in the doc. update this code in your .cs File and check.

    private void PerformBackgroundWork(object state)
    {
    try
    {
    tmrBackgroundInitializer.Change(50000, 50000);

          StartLocationUpdates();
    
            }
            catch (Exception objErr)
            {
                Log.Debug(TAG, objErr.ToString());
            }
            finally
            {
                tmrBackgroundInitializer.Change(TotalMillisecondsTmrForBackground, TotalMillisecondsTmrForBackground);
            }
    
        }
    

    Thanks
    Parthasarathy.S

  • RizwanZaidiRizwanZaidi USMember

    I have copied your code but still having the same problem.

  • ParthaSarathyParthaSarathy USMember ✭✭

    Can you Please share your code what you have done.

  • RizwanZaidiRizwanZaidi USMember

    Here is the source code

  • RizwanZaidiRizwanZaidi USMember

    Thanks it's working now, can you please explain your code so i know what i was doing wrong.

  • @ParthaSarathy
    Thank you so much your code solved my problem too. :smile::wink:

  • selvakrselvakr USMember ✭✭

    Thanks for this Code...
    And i have a small issue ,this code not working in android marshmallow, i used permission code but it not working please anyone can give solution for this problem.

  • PD.6026PD.6026 USMember ✭✭
    edited July 2017

    Hi @ParthaSarathy . I have a requirement of fetching user location once the app gets installed and update the location to server. The service will run till the app is installed in device even if the app is closed or terminated. My app is running well for first time use. If the user terminates the app and opens it second time and again terminates it, the app crashes after sometime and the crash notification displays 2 times. Can anyone please help what is wrong with the code.
    service-

    namespace Test
    {
        [Service]
        public class ServiceUpdateLocation : Service, ILocationListener
        {
            public event EventHandler<LocationChangedEventArgs> LocationChanged = delegate { };
            public event EventHandler<ProviderDisabledEventArgs> ProviderDisabled = delegate { };
            public event EventHandler<ProviderEnabledEventArgs> ProviderEnabled = delegate { };
            public event EventHandler<StatusChangedEventArgs> StatusChanged = delegate { };
            UpdateLocationModel curlocation = new UpdateLocationModel();
            readonly IAuthService _authService = IoC.Resolve<IAuthService>();
    
    
            public ServiceUpdateLocation()
            {
            }
            protected LocationManager LocMgr = Android.App.Application.Context.GetSystemService("location") as LocationManager;
    
            readonly string logTag = "LocationService";
            IBinder binder;
    
            public override void OnCreate()
            {
                base.OnCreate();
    
            }
    
            public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
            {
                if (intent != null)
                {
                    StartLocationUpdates();
                    return StartCommandResult.Sticky;
                }
                else
                    return StartCommandResult.Sticky;
            }
    
            public override IBinder OnBind(Intent intent)
            {
                try
                {
                    if (intent != null)
                    {
                        binder = new LocationServiceBinder(this);
                        return binder;
                    }
                    else
                        return null;
                }
                catch(Exception ex)
                {
    
                    return null;
                }
            }
    
            public void StartLocationUpdates()
            {
                //if (timerBackgroundInitializer == null)
                //    timerBackgroundInitializer = new Timer(new TimerCallback(UpdateLocation), null, 3000, 3000);
                //else
                //    timerBackgroundInitializer.Change(6000, 6000);
    
                try
                {
                    var locationCriteria = new Criteria();
    
                    locationCriteria.Accuracy = Accuracy.Fine;
                    locationCriteria.PowerRequirement = Power.NoRequirement;
    
                    var locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
    
                    LocMgr.RequestLocationUpdates(locationProvider, 1000, 0, this);
    
                }
                catch (Exception ex) { }
            }
    
            public override void OnDestroy()
            {
                base.OnDestroy();
               // Log.Debug(logTag, "Service has been terminated");
    
    
                //LocMgr.RemoveUpdates(this);
            }
    
            #region ILocationListener implementation
    
    
            public void OnLocationChanged(Android.Locations.Location location)
            {
                try
                {
                    this.LocationChanged(this, new LocationChangedEventArgs(location));
    
                    LocationContainer.CurrentLocation.Latitude = location.Latitude;
                    LocationContainer.CurrentLocation.Longitude = location.Longitude;
    
                    UpdateLocation();
                }
                catch (Exception ex) { }
    
            }
    
            private async void UpdateLocation()
            {
                try
                {
    
                        curlocation.Latitude = LocationContainer.CurrentLocation.Latitude;
                        curlocation.Longitude = LocationContainer.CurrentLocation.Longitude;
                        var result = await _authService.UpdateLocation(curlocation);
    
                }
                catch (Exception ex) { }
            }
    
            public void OnProviderDisabled(string provider)
            {
                this.ProviderDisabled(this, new ProviderDisabledEventArgs(provider));
            }
    
            public void OnProviderEnabled(string provider)
            {
                this.ProviderEnabled(this, new ProviderEnabledEventArgs(provider));
            }
    
            public void OnStatusChanged(string provider, Availability status, Bundle extras)
            {
                this.StatusChanged(this, new StatusChangedEventArgs(provider, status, extras));
            }
    
            #endregion
    
        }
    
        public class LocationServiceBinder : Binder
        {
            ServiceUpdateLocation service;
    
            public LocationServiceBinder(ServiceUpdateLocation service)
            {
                try
                {
                    this.service = service;
                }
                catch (Exception ex) { }
            }
    
            public ServiceUpdateLocation GetLocationServiceBinder()
            {
                try
                {
                    return service;
                }
                catch (Exception ex) { return null; }
            }
        }
    
    }
    

    I am calling the service in Main activity's OnCreate() -

    if (!isMyServiceRunning(typeof(ServiceUpdateLocation)))
    {
          StartService(new Intent(this, typeof(ServiceUpdateLocation)));
     }
    
  • mtimmermmtimmerm USMember ✭✭
    edited March 2018

    @PD.6026 , Did you found a solution for this and could you share it?

Sign In or Register to comment.