【问题标题】:Xamarin iOS Background taskXamarin iOS 后台任务
【发布时间】:2021-06-26 12:49:56
【问题描述】:
我在 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();
}
【问题讨论】:
标签:
c#
ios
xamarin
xamarin.forms
【解决方案1】:
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);
}
}