C# -> Android (Xamarin) -> start task every 5 minutes in Background-ThrowExceptions

Exception or error:

i want to run a task every 5 minutes. i’ve tried to solve it with an IntentService and AlarmManager, my code:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);

    var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
    var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);

    long interval = 5000;
    var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;

    var am = (AlarmManager)GetSystemService(Context.AlarmService);

    am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);

    Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}

i receive the toast, that the service is started, but if i look in running services, there is no service for my application. Can you tell me where the problem ist?

How to solve:

IntentService in an “activity” (if we can call it) runing in Background of the app, so finnally it will call the OnDestroy() ..
You can use the timer to fix your problem , like :

using System;
using System.Threading;

class TimerExampleState {
    public int counter = 0;
    public Timer tmr;
}

class App {
   public static void Main() {
    TimerExampleState s = new TimerExampleState();

    // Create the delegate that invokes methods for the timer.
    TimerCallback timerDelegate = new TimerCallback(CheckStatus);

    // Create a timer that waits one second, then invokes every second.
    Timer timer = new Timer(timerDelegate, s, 1000, 1000);

    // Keep a handle to the timer, so it can be disposed.
    s.tmr = timer;

    // The main thread does nothing until the timer is disposed.
    while (s.tmr != null)
        Thread.Sleep(0);
    Console.WriteLine("Timer example done.");
   }
   // The following method is called by the timer's delegate.

   static void CheckStatus(Object state) {
    TimerExampleState s = (TimerExampleState) state;
    s.counter++;
          Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
        if (s.counter == 5) {
        // Shorten the period. Wait 10 seconds to restart the timer.
        (s.tmr).Change(10000,100);
        Console.WriteLine("changed...");
    }
        if (s.counter == 10) {
        Console.WriteLine("disposing of timer...");
        s.tmr.Dispose();
        s.tmr = null;
    }
   }
}

Source : https://developer.xamarin.com/api/type/System.Threading.Timer/

###

Hope this code helps you:-

async void StartTimer()
{
   await Task.Delay(60000); //60 seconds
   // Do your code
   StartTimer(); // Again Call 
}

Call “StartTimer()” method where you want to. Call only once time then it calls automatically after 60 seconds.

Thanks !!!

###

you can create your own timer using xamarin forms device class

sample timer class:

public class Timer    {
        public Timer(int interval)
        {
            _interval = TimeSpan.FromMilliseconds(interval);
        }

        private bool _isRunning;
        private readonly TimeSpan _interval;

        private Action Tick;

        public void Start(Action tick)
        {
            _isRunning = true;
            Tick = tick;
            Xamarin.Forms.Device.StartTimer(_interval,() =>
            {
                Tick?.Invoke();
                return _isRunning;
            });
        }

        public void Stop()
        {
            _isRunning = false;
            Tick = null;
        }
    }

###

Create a service class. Call DoWork method in OnStartCommand method. Check whether the log is getting printed after every 5 seconds.

 public void DoWork()
            {
                var t = new Thread(() =>
                {
                    while (true)  
                    {
                       Log.Debug("Service", "Service running");    
                        Thread.Sleep(5000);
                    }
                });
                t.Start();
            }

Leave a Reply

Your email address will not be published. Required fields are marked *