我想实现JobScheduler,它可以很好地替代传统的后台服务。我尝试测试一种简单的方案,即在应用程序进入后台或关闭时启动Job Scheduler。应用程序开始打开或恢复时,作业计划程序将被取消。为此,我在App类中编写了以下代码
protected override void OnStart()
{
var message = new StopLongRunningTaskMessage();
MessagingCenter.Send(message, "StopLongRunningTaskMessage");
}
protected override void OnSleep()
{
var message = new StartLongRunningTaskMessage();
MessagingCenter.Send(message, "StartLongRunningTaskMessage");
}
protected override void OnResume()
{
var message = new StopLongRunningTaskMessage();
MessagingCenter.Send(message, "StopLongRunningTaskMessage");
}
MainActivity类中的OnCreate方法具有以下代码:
MessagingCenter.Subscribe(this, "StartLongRunningTaskMessage", message =>
{
if (!IsJobServiceOn())
{
_jobScheduler = (JobScheduler)GetSystemService(JobSchedulerService);
var extra = new PersistableBundle();
extra.PutInt("LoopCount", 20);
var javaClass = Java.Lang.Class.FromType(typeof(MyFirstservice));
var compName = new ComponentName(this, javaClass);
var jobInfo = new JobInfo.Builder(1, compName)
.SetPersisted(true)
.SetExtras(extra)
.SetPeriodic(900000)
.Build();
var result = _jobScheduler.Schedule(jobInfo);
}
});
MessagingCenter.Subscribe<StopLongRunningTaskMessage>(this, "StopLongRunningTaskMessage", message => {
if (IsJobServiceOn())
_jobScheduler.Cancel(1);
});
}
private bool IsJobServiceOn()
{
JobScheduler scheduler = (JobScheduler)GetSystemService(JobSchedulerService);
if (scheduler.GetPendingJob(1) != null)
return true;
else
return false;
}
只要未将应用程序刷出或完全关闭,JobScheduler即可正常工作。我真的不知道为什么从最近的应用程序列表中拔出应用程序后重新启动后,应用程序会崩溃。
谢谢您的帮助。