IOS后台持续运行对于c#程序员不懂得ios后台机制的是存在一定困扰的。特别是ios9过后对后台和安全进行了更严格的限制
好了废话不多说
一 设置info.plist权限信息
参考:http://www.jianshu.com/p/e54751348abe
需要开启后台运行模式:勾选位置更新,音频播放
二 关键代码
2.1 设置
coo.DistanceFilter = -1;//设置两点之间位置精度,即手机不动也会提示 coo.DesiredAccuracy = CLLocation.AccuracyBest; coo.AllowsBackgroundLocationUpdates = true;//开启后台持续定位 coo.PausesLocationUpdatesAutomatically = false;//禁用后台暂停位置更新 coo.Delegate = this; coo.RequestAlwaysAuthorization(); coo.StartUpdatingLocation(); coo.StartUpdatingHeading();
2.2 前后台切换
public override void DidEnterBackground(UIApplication uiApplication) { //进入后台 DependencyService.Get<ILocationManager>().EnterBackground(); } public override void WillEnterForeground(UIApplication uiApplication) { //进入前台 DependencyService.Get<ILocationManager>().EnterForground(); }
三 播放音频(系统提示音)
var sound = new SystemSound(1007); await sound.PlaySystemSoundAsync();
四 实现结果
当位置发生更新时播放系统提示音,且伴有震动,这里暂时对ios消息推送不甚了解,下次将在位置更新播放提示音同时加入本地推送
这里是使用xamarin.ios 原生api实现,之前试过百度地图持续最新sdk弄了半天进入后台就不行了,也许是我知识不够,但是使用原生api也行那么也就不用那么麻烦了
五 完整代码
[assembly: Dependency(typeof(MyLocationManager))] namespace Xamarin.Simples.iOS { public class MyLocationManager : NSObject, ICLLocationManagerDelegate, ILocationManager { private CLLocationManager coo; private bool init = false; public MyLocationManager() { coo = new CLLocationManager(); } #region ICLLocationManagerDelegate #region IDisposable implementation void IDisposable.Dispose() { throw new NotImplementedException(); } #endregion #region INativeObject implementation IntPtr ObjCRuntime.INativeObject.Handle { get { throw new NotImplementedException(); } } #endregion [Foundation.Export("locationManager:didUpdateLocations:")] public async void LocationsUpdated(CoreLocation.CLLocationManager manager, CoreLocation.CLLocation[] locations) { Console.WriteLine("定位成功"); var sound = new SystemSound(1007); await sound.PlaySystemSoundAsync(); } [Export("locationManager:didUpdateHeading:")] public void UpdatedHeading(CoreLocation.CLLocationManager manager, CoreLocation.CLHeading newHeading) { } [Foundation.Export("locationManager:didUpdateToLocation:fromLocation:")] public void UpdatedLocation(CoreLocation.CLLocationManager manager, CoreLocation.CLLocation newLocation, CoreLocation.CLLocation oldLocation) { } #endregion public void Init() { if (!init) { coo.DistanceFilter = -1; coo.DesiredAccuracy = CLLocation.AccuracyBest; coo.AllowsBackgroundLocationUpdates = true; coo.PausesLocationUpdatesAutomatically = false; coo.Delegate = this; coo.RequestAlwaysAuthorization(); coo.StartUpdatingLocation(); coo.StartUpdatingHeading(); init = true; } } public void EnterBackground() { if (init) coo.StartMonitoringSignificantLocationChanges(); } public void EnterForground() { if (init) coo.StopMonitoringSignificantLocationChanges(); } } }
六 案例下载
https://yunpan.cn/cqegpGW96nYx7 (提取码:4508)
时间: 2024-10-28 11:06:02