我正在开发一个GPS车辆地理定位应用程序..如果用户在应用程序设置中激活通知,则必须每X分钟开始检查服务器,以验证是否有新的车辆警报。为此,我需要一个服务,当应用程序在前台工作,并继续工作,即使用户把应用程序在后台继续搜索通知。
所以我试着这样做(AppDelegate):
public override void DidEnterBackground(UIApplication application)
{
if (Preferences.Get(nameof(App.IsNotificationsServiceRunning), false))
{
nint taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => { });
new Task(() => {
DoWork();
UIApplication.SharedApplication.EndBackgroundTask(taskID);
}).Start();
}
else
{
return;
}
}
//TIMER
public void DoWork()
{
var minutes = TimeSpan.FromMinutes(2);
Device.StartTimer(minutes, () => {
//check for notifications
checkNotificationsFromServer();
// Returning true means repeat this timer
return true;
});
}
public void checkNotificationsFromServer(){
//Some code here...
}这段代码的问题是..首先,应用程序永远不会检查通知,直到它被放在后台!第二(有点奇怪),但是这个解决方案在iOS模拟器上有效,但在物理设备(IPhone11)上不起作用!这意味着当应用程序在后台时,永远不会调用checkNotificationsFromServer()!
有什么建议吗?
发布于 2020-09-09 21:00:39
有几种方法可以实现你想要的。
这里有Background Modes (deprecated in iOS 13.0),
这里有Background Tasks (iOS 13.0+),
https://stackoverflow.com/questions/63808669
复制相似问题