how can break a loop by button click???

I have developed a simple app for android which update location every minutes and send it to a server for more process.
Now I have two question:
1- How can rise GetLocation function every minutes??? I use a while loop and Thread.Sleep() function right now, but I believe there is better solution.
2- How can break loop by button click???

Best Answer

Answers

  • JohannesHerterJohannesHerter USMember ✭✭
    edited July 2016

    Take a look at the xamarin documentation on Location Services

    What you want to do is get the LocationManager and subsribe to the location updates (this code is also seen in the link provided):

    LocationManager locMgr;
    
    locMgr = GetSystemService (Context.LocationService) as LocationManager;
    
    string Provider = LocationManager.GpsProvider;
    
        if(locMgr.IsProviderEnabled(Provider))
        {
          locMgr.RequestLocationUpdates (Provider, 1000, 0, this);
        }
        else
        {
          Log.Info(tag, Provider + " is not available. Does the device have location services enabled?");
        }
    

    The last parameter is an Implementation of ILocationListener (also from the link provided):

    public class MainActivity : Activity, ILocationListener
    {
      ...
    
      public void OnProviderEnabled (string provider)
      {
        ...
      }
      public void OnProviderDisabled (string provider)
      {
        ...
      }
      public void OnStatusChanged (string provider, Availability status, Bundle extras)
      {
        ...
      }
      public void OnLocationChanged (Android.Locations.Location location)
      {
        ...
      }
    }
    

    To stop updates you have to call RemoveUpdates with your listener on the LocationManager:

    locMgr.RemoveUpdates (this);
    
  • AlirezaToosiAlirezaToosi USMember

    I do not have problem for getting location. I have used Geolocator component to reach that. My question is how can
    call it for example every 5 minutes??? I need to update my location every 5 minutes.

  • AlirezaToosiAlirezaToosi USMember
    edited July 2016

    Tanks @BernardoSalgueiro.0082

    I have used Geolocator component to receive my location.

    I used System.Timers.Timer to achieve that:

            System.Timers.Timer timer1 = new System.Timers.Timer();
             timer1.Elapsed += (s, e) => timer1_Tick(s, e).SwallowException();
             timer1.Interval = 10000;
             timer1.Enabled = true;
             timer1.AutoReset = true
    
      private async Task timer1_Tick(object sender, ElapsedEventArgs args)
            {
                await GetLocationCompatAsync();
            }
    
Sign In or Register to comment.