Xamarin 服务 - 根据时间表运行 [英] 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?
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.
这篇关于Xamarin 服务 - 根据时间表运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!