ArturM
ArturM

Reputation: 239

Xamarin service - run according to a time schedule

I am developing an app built on this example: https://github.com/xamarin/mobile-samples/tree/master/BackgroundLocationDemo

The example works and the location updates are coming in as expected. However, Android keeps showing an notification that the service is running and draining battery. Now, all my users have a defined working schedule (list of Start to End DateTime per day e.g 8am-1pm, 4pm-8pm), and I want that the service is only running between those working times. This means that I need to start/stop the service whenever the schedule says the user is working or not.

I've asked this question before but wondering if anyone figured out an efficient and solid way to achieve this type of service that is operating from a time schedule?

Upvotes: 0

Views: 464

Answers (1)

Leon Lu
Leon Lu

Reputation: 9264

You can use AlarmManager to execute a task in specific time.

For example, I want my task running at the 10:51 am every day, I can use following code to execute it.

 public static void startAlarmBroadcastReceiver(Context context)
        {
            Intent _intent = new Intent(context, typeof( AlarmBroadcastReceiver));
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, _intent, 0);
            AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);
            // Remove any previous pending intent.
            alarmManager.Cancel(pendingIntent);

            Calendar cal = Calendar.Instance;
            cal.Set( CalendarField.HourOfDay, 10);
            cal.Set(CalendarField.Minute, 51);
            cal.Set(CalendarField.Second, 0);

            alarmManager.SetRepeating(AlarmType.RtcWakeup, cal.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);


       }

Here is code about AlarmBroadcastReceiver.

    [BroadcastReceiver(Enabled = true, Exported = false)]
    public class AlarmBroadcastReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
        }
    }

Do not forget to add following permissions.

<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

Here is running gif. enter image description here

Upvotes: 2

Related Questions