Xamarin,Android - 当我关闭应用程序时服务停止工作

时间:2017-09-20 16:21:47

标签: android xamarin service

我试图让android服务在后台检查设备位置。当用户或代码中的特定条件将其停止时,服务应该始终有效。

当我关闭应用程序,然后服务停止和崩溃应用程序时,服务工作正常。

你能告诉我我做错了什么。

[assembly: Dependency(typeof(CheckPositionService))]
namespace GNote.Droid.Models
{
    [Service(Name = "GNote.Service", Exported = true)]
    public class CheckPositionService : Service, IMapService
    {
        private CheckPositionServiceBinder binder;
        private CheckPositionServiceConnection ServiceConnection;
        public override void OnCreate()
        {
            base.OnCreate();
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        this.startCheckingPosition();
        var ongoing = new Notification(Resource.Drawable.icon, "Test");
        StartForeground(1000, ongoing);
        return StartCommandResult.Sticky;
    }

        public override IBinder OnBind(Intent intent)
        {
            binder = new CheckPositionServiceBinder(this);           
            return binder;
        }

        public void StartServ()
        {
            Android.MainActivity.AndroidContext.StartService(new Intent(Android.MainActivity.AndroidContext, typeof(CheckPositionService)));
        }

类MapPosition。

public static class MapPosition
    {
        private static List<Note> notes;

        public static async void getFromDB()
        {
            notes = await DataBaseService.getMapAlarmActiveNotes();
            if (notes.Count == 0)
            {
                await StopListening();               
            }
            else
            {
                await StartListening();                
            }

        }

        public static async Task StartListening()
        {            
            if (CrossGeolocator.Current.IsListening)
                return;

            await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true);

            CrossGeolocator.Current.PositionChanged += PositionChanged;
            CrossGeolocator.Current.PositionError += PositionError;
        }

        private static void PositionChanged(object sender, PositionEventArgs e)
        {

            sendNotification(e.Position.Longitude+" POS "+e.Position.Latitude);

        }

        private static async void PositionError(object sender, PositionErrorEventArgs e)
        {
            await StopListening();
            Console.WriteLine(e.Error);
            //Handle event here for errors
            await StartListening();
        }

        public static async Task StopListening()
        {
            if (!CrossGeolocator.Current.IsListening)
                return;

            await CrossGeolocator.Current.StopListeningAsync();

            CrossGeolocator.Current.PositionChanged -= PositionChanged;
            CrossGeolocator.Current.PositionError -= PositionError;
        }

谢谢。

0 个答案:

没有答案