Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Xamarin forms background service to get location updates?

DharumaRajDharumaRaj USMember ✭✭
edited October 2016 in Xamarin.Forms

Hello everyone,
->In my Xamarin forms Shared project I have added a service (LocationUpdateService) and an alarm manager to get location updates for ever 3mins.
-> I'm getting Location updates when my application is online ((i.e) When when my application is not closed).
-> My problem is that when I close my application I'm not able to get location updates in background.
->Is there any special permission in Xamarin forms for background services that I have to specify??
below is my code.
`namespace ETMS.Droid.Service
{
[Service(Exported = true)]
class LocationUpdateService : Android.App.Service, ILocationListener
{
private enum State
{
IDLE,
WORKING
}

    private static State state;
    private LocationManager locationManager;
    private PowerManager.WakeLock wakeLock;

    static LocationUpdateService()
    {
        state = State.IDLE;
    }

    public override void OnCreate()
    {
        base.OnCreate();
        PowerManager pm = (PowerManager) GetSystemService(Context.PowerService);
        this.wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "LocationUpdateService");
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        if (state == State.IDLE)
        {
            state = State.WORKING;
            this.wakeLock.Acquire();

            // Location request
            locationManager = (LocationManager) GetSystemService(Context.LocationService);
            Criteria c = new Criteria();
            c.Accuracy = Accuracy.Coarse;
            string PROVIDER = locationManager.GetBestProvider(c, true);
            locationManager.RequestLocationUpdates(PROVIDER, 3000, 0, this);

        }
        return StartCommandResult.Sticky;

    }

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

    public void OnLocationChanged(Location location)
    {
        locationManager.RemoveUpdates(this);
        Toast.MakeText(ApplicationContext, "Lat:" + location.Latitude + "Lng:" + location.Longitude,
            ToastLength.Long).Show();
        SendToServer(location);
    }

    public override void OnDestroy()
    {
        base.OnDestroy();
        state = State.IDLE;
        if (this.wakeLock.IsHeld)
        {
            this.wakeLock.Release();
        }
    }

    public void OnProviderDisabled(string provider)
    {

    }

    public void OnProviderEnabled(string provider)
    {

    }

    public void OnStatusChanged(string provider, Availability status, Bundle extras)
    {

    }

    private void SendToServer(Location location)
    {
        Task.Factory.StartNew(() =>
        {
            bool authenticate = ETMS.Entity.Helpers.AuthenticateWithSharePoint();
            string userName = Settings.UserName;
            if (authenticate)
            {
                SharepointService.UpdateLocationToServer(userName, location.Latitude, location.Longitude);
            }
        }).ContinueWith(task =>
        {
            try
            {
                OnSendingFinished();
            }
            catch (Exception)
            {
                Toast.MakeText(ApplicationContext,"Exception Reacged",ToastLength.Long).Show();
                throw;
            }

        });

    }

    private void OnSendingFinished()
    {
        this.StopSelf();
    }
}

}and my broadcast receiver class.namespace ETMS.Droid.Receiver
{
[BroadcastReceiver(Enabled = true,Exported = true)]
[IntentFilter(new string[] { "android.net.conn.CONNECTIVITY_CHANGE" })]
class ConnectivityReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{

        AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
        PendingIntent wakeupIntent = PendingIntent.GetService(context, 0 ,new Intent(context,typeof(LocationUpdateService)),PendingIntentFlags.UpdateCurrent);
        bool hasNetwork = !intent.GetBooleanExtra(ConnectivityManager.ExtraNoConnectivity, false);
        if (hasNetwork)
        {
            Toast.MakeText(context,"Reached Receiver",ToastLength.Long).Show();
            // start service now for doing once
            context.StartService(new Intent(context, typeof(LocationUpdateService)));

            //Schedule service for every 2 minutes
            alarmManager.SetInexactRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 120000,120000, wakeupIntent);
        }
        else
        {
            alarmManager.Cancel(wakeupIntent);
        }
    }
}

}`
can anyone help me with this please.

Sign In or Register to comment.