user5084971
user5084971

Reputation:

Background Services in Xamarin.Android

I'm struggling to create a background service using Xamarin.Android. The background service should work every 5 minutes and also should work when the phone's screen off or the application closed. Do you have any idea how to achieve this. I found that library and it's working fine but the problem is interval is not working under 15 minutes. I don't know why.

https://www.c-sharpcorner.com/article/scheduling-work-with-workmanager-in-android/

I'm looking forward for your kind supports. Thank you.

Upvotes: 2

Views: 1482

Answers (2)

picolino
picolino

Reputation: 5459

I think BroadcastReceiver will be more appropriate for your task. It provides more flexibility and setting parameters.

Declaring broadcast receiver:

using Android.Content;

[BroadcastReceiver]
public class BackgroundBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        // Your code here that will be executed periodically
    }
}

Broadcast receiver registration:

// context - any of your Android activity

var intentAlarm = new Intent(context, typeof(BackgroundBroadcastReceiver));
var alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);

alarmManager.SetRepeating(AlarmType.ElapsedRealtime, // Works even application\phone screen goes off
                          DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), // When to start (right now here)
                          1000, // Receiving interval. Set your value here in milliseconds.
                          PendingIntent.GetBroadcast(context, 1, intentAlarm, PendingIntentFlags.UpdateCurrent));

Upvotes: 1

hadilionson
hadilionson

Reputation: 96

you can use service like bellow code

using System;
using System;
using System.Threading;
using Android.App;
using Android.Content;
using Android.OS;
using OomaAndroid.Models;
using SQLite;

namespace OomaAndroid
{
    [Service]
    public class ServiceTest : Service
    {
        Timer timer;        
        public override void OnCreate()
        {
            base.OnCreate();
        }
        public override IBinder OnBind(Intent intent)
        {            
            return null;
        }


        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {            
            timer = new Timer(HandleTimerCallback, 0, 0, 900000);
            return base.OnStartCommand(intent, flags, startId);
        }

        private void HandleTimerCallback(object state)
        {
            //this part codes will run every 15 minutes
        }
    }    
}

also you can run service in the MainActivity

      Intent intSer = new Intent(base.ApplicationContext, typeof(OomaService));
      StartService(intSer);

also you should get Receive_Boot_Compeleted permission From user to run service after restarting cellphone

Upvotes: 0

Related Questions