Xamarin iOS后台任务



我正在Xamarin Forms应用程序中工作,我正在尝试为iOS制作后台任务。只有当我第一次在手机上部署时才有效。之后,当我锁上手机时,什么也没发生。这是我的代码:

nint taskID;
public void Background()
{
new Task(() =>
{
taskID = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
UIApplication.SharedApplication.EndBackgroundTask(taskID);
});
//what to do
UIApplication.SharedApplication.EndBackgroundTask(taskID);
}).Start();
}

BeginBackgroundTask将延长应用程序的后台执行时间,确保您有足够的时间执行关键任务。

您可以使用此属性UIApplication.SharedApplication.BackgroundTimeRemaining查找扩展时间。这是一个倒计时计时器。当应用程序处于后台时,此值将减小,并在时间到期后停止。

nint taskID;
private async Task Background()
{
taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => BGTimeExpired());
await DoYourTask() //Start your task which you wanted to do when application goes to background. If you have already started your task and here just you wanted to extend the background operation time then. Add while loop [while (UIApplication.SharedApplication.BackgroundTimeRemaining > 5) await Task.Delay(1000);]

//if your task completed before background time expired. Then call BGTimeExpired()
BGTimeExpired();
}
private void BGTimeExpired()
{
//Safely end your on going task here
if (taskID != default(nint))
{
UIApplication.SharedApplication.EndBackgroundTask(taskID); //End background task
taskID = default(nint);
}
}
public override void DidEnterBackground(UIApplication application)
{
base.DidEnterBackground(application);
Background();
}
public override void WillEnterForeground(UIApplication application)
{
base.WillEnterForeground(application);
if (taskID != default(nint))
{
UIApplication.SharedApplication.EndBackgroundTask(taskID);
taskID = default(nint);
}
}

最新更新