Xamarin service - run according to a time schedule

主宰稳场 提交于 2020-05-17 07:42:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/61353360/xamarin-service-run-according-to-a-time-schedule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!