简体   繁体   English

前台服务中的位置更新

[英]Location updates in Foreground Service

I am trying to implement an app for navigating a user in the background.我正在尝试实现一个用于在后台导航用户的应用程序。 I am running a foreground service.我正在运行前台服务。 But for RequestLocationUpdates I have two options:但是对于RequestLocationUpdates我有两个选择:

  1. Use PendingIntent (usually this one used for background)使用PendingIntent (通常这个用于背景)
  2. Use LocationCallback使用LocationCallback

Which one should be used for Location updates in foreground?哪一个应该用于前台的位置更新? I think LocationCallback , but not sure.我认为LocationCallback ,但不确定。

Thanks in advance.提前致谢。

When you use RequestLocationUpdates to update the location in the foreground service, please achieve Android.Locations.ILocationListener interface and achieve the OnLocationChanged method.在前台服务中使用RequestLocationUpdates更新位置时,请实现Android.Locations.ILocationListener接口并实现OnLocationChanged方法。

Here is some related code这是一些相关的代码

 [Service]
    public class LocationService : Service, ILocationListener
    {
        const int SERVICE_RUNNING_NOTIFICATION_ID = 123;
        const string NOTIFICATION_CHANNEL_ID = "com.company.app.channel";

        readonly string logTag = "LocationService";
        IBinder binder;

        // Set our location manager as the system location service
        protected LocationManager LocMgr = Application.Context.GetSystemService("location") as LocationManager;

        // ILocationListener is a way for the Service to subscribe for updates
        // from the System location Service

        public void OnLocationChanged(Android.Locations.Location location)
        {
            LocationChanged(this, new LocationChangedEventArgs(location));

            // This should be updating every time we request new location updates
            // both when teh app is in the background, and in the foreground
            Log.Debug(logTag, $"Latitude is {location.Latitude}");
            Log.Debug(logTag, $"Longitude is {location.Longitude}");
            Log.Debug(logTag, $"Altitude is {location.Altitude}");
            Log.Debug(logTag, $"Speed is {location.Speed}");
            Log.Debug(logTag, $"Accuracy is {location.Accuracy}");
            Log.Debug(logTag, $"Bearing is {location.Bearing}");
        }

        public void OnProviderDisabled(string provider)
        {
            ProviderDisabled(this, new ProviderDisabledEventArgs(provider));
        }

        public void OnProviderEnabled(string provider)
        {
            ProviderEnabled(this, new ProviderEnabledEventArgs(provider));
        }

        public void OnStatusChanged(string provider, Availability status, Bundle extras)
        {
            StatusChanged(this, new StatusChangedEventArgs(provider, status, extras));
        }

        public event EventHandler<LocationChangedEventArgs> LocationChanged = delegate { };
        public event EventHandler<ProviderDisabledEventArgs> ProviderDisabled = delegate { };
        public event EventHandler<ProviderEnabledEventArgs> ProviderEnabled = delegate { };
        public event EventHandler<StatusChangedEventArgs> StatusChanged = delegate { };

        public override void OnCreate()
        {
            base.OnCreate();
            Log.Debug(logTag, "OnCreate called in the Location Service");
        }

        // This gets called when StartService is called in our App class
        [Obsolete("deprecated in base class")]
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(logTag, "LocationService started");

            // Check if device is running Android 8.0 or higher and call StartForeground() if so
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                                   .SetContentTitle(Resources.GetString(Resource.String.app_name))
                                   .SetContentText(Resources.GetString(Resource.String.notification_text))
                                   .SetSmallIcon(Resource.Drawable.notification_icon_background)
                                   .SetOngoing(true)
                                   .Build();

                var notificationManager =
                    GetSystemService(NotificationService) as NotificationManager;

                var chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "On-going Notification", NotificationImportance.Min);

                notificationManager.CreateNotificationChannel(chan);

                StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
            }

            return StartCommandResult.Sticky;
        }

        // This gets called once, the first time any client bind to the Service
        // and returns an instance of the LocationServiceBinder. All future clients will
        // reuse the same instance of the binder
        public override IBinder OnBind(Intent intent)
        {
            Log.Debug(logTag, "Client now bound to service");

            binder = new LocationServiceBinder(this);
            return binder;
        }

        // Handle location updates from the location manager
        public void StartLocationUpdates()
        {
            //we can set different location criteria based on requirements for our app -
            //for example, we might want to preserve power, or get extreme accuracy
            var locationCriteria = new Criteria();

            locationCriteria.Accuracy = Accuracy.NoRequirement;
            locationCriteria.PowerRequirement = Power.NoRequirement;

            // get provider: GPS, Network, etc.
            var locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
            Log.Debug(logTag, string.Format("You are about to get location updates via {0}", locationProvider));

            // Get an initial fix on location
            LocMgr.RequestLocationUpdates(locationProvider, 2000, 0, this);

            Log.Debug(logTag, "Now sending location updates");
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            Log.Debug(logTag, "Service has been terminated");

            // Stop getting updates from the location manager:
            LocMgr.RemoveUpdates(this);
        }
    }
}

Here is my demo, you can refer to it.这是我的demo,大家可以参考。

https://github.com/851265601/XAndroidLocation https://github.com/851265601/XAndroidLocation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 前台服务在 Oreo 中 10 分钟后停止提供位置更新 - Foreground service stops giving location updates after 10 minutes in Oreo 前台服务未在Android O中的打盹模式下接收位置更新 - Foreground service not receiving location updates in Doze mode in Android O 一旦完成处理,带有位置更新的Android前台服务将被杀死 - Android foreground service with location updates gets killed once onHandle completed 有时间间隔的requestlocationupdates无法在Foreground Service中获取位置更新? - requestlocationupdates with time interval not getting location updates in Foreground Service? Android位置前景服务 - Android Foreground Service For Location 当用户看不到活动时,前台服务 Android Q(XIAOMI 设备)中没有位置更新 - No location updates in foreground service Android Q(XIAOMI device) when activity is not visible to user 屏幕关闭时,前台服务未在 Android 7.0+ 中接收位置更新 - Foreground service not receiving location updates in Android 7.0+ when screen is off 当应用程序移至后台时,在前台服务中获取位置更新不起作用 - getting location updates in foreground service isn't working when app is moved to background 通过服务进行位置更新 - Location Updates through a service 服务未收到位置更新 - Service not receiving location updates
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM