c# - 当我的应用程序在后台时,如何在 UWP 中获取实时位置更新?
问题描述
我正在为我的工作开展的一个项目支持位置跟踪,我们最近决定在我们的应用程序处于后台时添加对位置跟踪的支持。我们支持以下平台:iOS、Android 和 UWP。正如标题所暗示的,我正在寻求在 UWP(桌面和手机)上实现此功能的帮助。我想知道是否有人可以帮助我或为为 UWP 编写 GPS/跑步跟踪应用程序的人指出一些代码。
我已经尝试过扩展执行会话和后台任务。事实上,我目前在我的应用程序中同时使用这两种方法,但在 UWP 上使用背景跟踪方面都没有太多运气。我们使用的定位服务是基于MvvmCross UWP Location Watcher的自定义代码。作为参考,该项目的一些摘录App.xaml.cs
:
// This method is associated with the LeavingBackground event
private async void WillEnterForeground(object sender, LeavingBackgroundEventArgs e)
{
if (_trackingNotificationTask == null)
{
await BackgroundExecutionManager.RequestAccessAsync();
RegisterTrackingNotificationTask();
}
if (_backgroundTrackingSession == null)
{
using (var backgroundSession = new ExtendedExecutionSession())
{
backgroundSession.Reason = ExtendedExecutionReason.LocationTracking;
backgroundSession.Description = "Track Responder Location in Background";
backgroundSession.Revoked += OnSessionRevoked;
var result = await backgroundSession.RequestExtensionAsync();
switch (result)
{
case ExtendedExecutionResult.Allowed:
_backgroundTrackingSession = backgroundSession;
break;
}
}
}
var locationService = Mvx.Resolve<ILocationService>();
locationService?.Resume();
if (_appInBackground)
{
ClearAllNotifications();
if (_backgroundTrackingTask != null)
{
_backgroundTrackingTask.Unregister(true);
_backgroundTrackingTask = null;
}
await Mvx.Resolve<IEventInformationSyncService>().SyncUserSetting();
await Mvx.Resolve<IAppService>().IsMobileStatusGood();
_appInBackground = false;
}
}
// This Method is associated with the EnteredBackground event
private void DidEnterBackground(object sender, EnteredBackgroundEventArgs e)
{
var deferral = e.GetDeferral();
// Request permission for background tracking
RegisterBackgroundTrackingTask();
var appSettingService = Mvx.Resolve<IAppSettingService>();
if (!NeedToUpgradeWindows() && Core.App.IsResponderTrackingEnabled()) // Are we in an event and is responder tracking enabled?
{
ShowNotification();
}
_appInBackground = true;
deferral.Complete();
}
private void RegisterBackgroundTrackingTask()
{
if (NeedToUpgradeWindows())
{
if (!_shownUpgradeMessage)
{
Mvx.Resolve<IUserInteraction>().Alert("Your current windows version does not support background tasks. Please upgrade to windows version 1709 or above to utilize background tasks.", () => { _shownUpgradeMessage = true; });
}
return;
}
var backgroundTrackingBuilder = new BackgroundTaskBuilder()
{
Name = BackgroundTrackingTask.Name,
TaskEntryPoint = typeof(BackgroundTrackingTask).FullName,
IsNetworkRequested = true
};
backgroundTrackingBuilder.SetTrigger(new TimeTrigger(15, false));
_backgroundTrackingTask = backgroundTrackingBuilder.Register();
_backgroundTrackingTask.Completed += OnBackgroundTrackingTaskCompleted;
}
private void RegisterTrackingNotificationTask()
{
if (NeedToUpgradeWindows())
{
if (!_shownUpgradeMessage)
{
Mvx.Resolve<IUserInteraction>().Alert("Your current windows version does not support background tasks. Please upgrade to windows version 1709 or above to utilize background tasks.", () => { _shownUpgradeMessage = true; });
}
return;
}
if (IsTaskRegistered(TrackingNotificationHandlerTask.Name))
{
return;
}
var notificationTaskBuilder = new BackgroundTaskBuilder()
{
Name = TrackingNotificationHandlerTask.Name,
TaskEntryPoint = typeof(TrackingNotificationHandlerTask).FullName
};
notificationTaskBuilder.SetTrigger(new ToastNotificationActionTrigger());
_trackingNotificationTask = notificationTaskBuilder.Register();
_trackingNotificationTask.Completed += OnNotificationActivated;
}
private void OnBackgroundTrackingTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
var settingValues = ApplicationData.Current.LocalSettings.Values;
var success = (bool)settingValues["Success"];
if (success)
{
var locationService = Mvx.Resolve<ILocationService>();
var location = new MvxGeoLocation
{
Coordinates = new MvxCoordinates
{
Latitude = (double)settingValues["Latitude"],
Longitude = (double)settingValues["Longitude"],
Accuracy = (double)settingValues["Accuracy"]
},
Timestamp = new DateTimeOffset(DateTime.Parse((string)settingValues["Time"]))
};
locationService.OnLocation(location, true);
}
}
private void OnNotificationActivated(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
var settings = ApplicationData.Current.LocalSettings;
var action = (string)settings.Values["NotificationAction"];
var locationService = Mvx.Resolve<ILocationService>();
switch (action)
{
case "pause":
locationService?.ClearResponderTrackingOptions();
break;
case "resume":
locationService?.RecycleResponderTracking();
break;
}
ClearAllNotifications();
ShowNotification();
}
提前非常感谢大家。如果你们还需要什么,请告诉我!
解决方案
推荐阅读
- primefaces - Primefaces数据表排序和对齐
- python - 编辑 python 包
- mysql - 在我的数据库中 - 错误 1062 Duplicate entry key PRIMARY
- javascript - 在 Node.js 中从 Elasticsearch 中获取大数据
- uwp - 错误 CS0433 类型“InstanceContext”同时存在于“System.ServiceModel.Duplex, Version=4.0.1.2,”和“System.ServiceModel, Version=4.0.0.0”中
- java - java.lang.AbstractMethodError:接收器类 org.springframework.cloud.bootstrap.BootstrapApplicationListener
- android - 如何使用此输入解析日期字符串 2019-08-06 08:26:17
- android - Android 蓝牙连接到 ELM327/OBD2 设备
- scheme - #f 输出 repl.it 中的方案结果
- java-8 - 多个延迟消费者、并发句柄、BlockingQueue