Android:屏幕关闭时服务停止工作(打瞌睡/应用程序待机模式)

Android:屏幕关闭时服务停止工作(打瞌睡/应用程序待机模式),android,xamarin.android,android-doze,android-doze-and-standby,Android,Xamarin.android,Android Doze,Android Doze And Standby,如果我每120秒发送一次GPS(Lat/Lon),我必须实施一项服务。让我休息一下 我的问题是,当屏幕关闭时,服务似乎停止工作 尝试使用StartedService和BroadcastReceiver 尝试使用IntentService和WakefulBroadcastReceiver 1。例如,该尝试适用于三星Galaxy X封面,但不适用于华为P9 Lite。请注意我关闭了华为手机的省电模式(电源应用程序)。所以,当屏幕关闭时,我的应用程序会继续运行。例如,10分钟后,我打开华为手机的屏幕,

如果我每120秒发送一次GPS(Lat/Lon),我必须实施一项服务。让我休息一下

我的问题是,当屏幕关闭时,服务似乎停止工作

  • 尝试使用StartedService和BroadcastReceiver
  • 尝试使用IntentService和WakefulBroadcastReceiver
  • 1。例如,该尝试适用于三星Galaxy X封面,但不适用于华为P9 Lite。请注意我关闭了华为手机的省电模式(电源应用程序)。所以,当屏幕关闭时,我的应用程序会继续运行。例如,10分钟后,我打开华为手机的屏幕,在运行服务时看到服务正在运行(已用秒数),因此我可以验证服务是否未关闭

    二,。当屏幕关闭时,尝试在任何手机上都不起作用

    当屏幕打开(无睡眠)时,两次尝试均正常工作

    注意:为了简洁起见,我去掉了不相关方法的代码(获取/传输gps数据)

    这是1的代码。尝试:

    服务

    [Service]
    public class GpsTrackerService : Service
    {
        private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerService).Name;
        private static readonly int NOTIFICATION_ID = 10000;
        private MobileServiceClient _mobileServiceClient;
    
        public TelephonyManager GetTelefonyManager()
        {
            return (Android.Telephony.TelephonyManager) GetSystemService(TelephonyService);
        }
    
        public bool IsRunningAsService { get; set; }
    
    
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(LogTag, "GpsTrackerService.OnStartCommand :: Service started. Timer instantiated.");
            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsights("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnStartCommand :: Service started.Timer instantiated.");
    
            Task.Run(async () =>
            {
                try
                {
                    await DoWork();
                    await Task.Delay(TimeSpan.FromMinutes(2));
                }
                catch (Exception e)
                {
                    Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.Message} Type:{e.GetType().Name}, Stacktrack:{e.StackTrace}");
                    if (e.InnerException != null)
                    {
                        Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.InnerException.Message} Type:{e.InnerException.GetType().Name}, Stacktrack:{e.InnerException.StackTrace}");
                    }
                    GpsTrackerServiceUtils.SendExceptionToApplicationInsights(e, LogTag, _mobileServiceClient, this);
                }
                finally
                {
                    // Restart Service
                    Intent broadcastIntent = new Intent(action: GpsConstants.GpsRestart);
                    SendBroadcast(broadcastIntent);
                }
    
            });
    
            return StartCommandResult.Sticky;
        }
    
          public override IBinder OnBind(Intent intent)
        {
            // This is a started service, not a bound service, so we just return null.
            return null;
        }
    }
    
     GpsTrackerServiceBroadcastReceiver = new GpsTrackerServiceBroadcastReceiver();
     RegisterReceiver(GpsTrackerServiceBroadcastReceiver, new IntentFilter(GpsConstants.GpsBroadcastReceiver));
    
    [Service]
    public class GpsTrackerIntentService : IntentService
    {
        private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerIntentService).Name;
        private static readonly int NOTIFICATION_ID = 10000;
        private MobileServiceClient _mobileServiceClient;
    
        public TelephonyManager GetTelefonyManager()
        {
            return (TelephonyManager) GetSystemService(TelephonyService);
        }
    
        protected override async void OnHandleIntent(Intent intent)
        {
            try
            {
                // perform task
                await Bootstrap();
    
                GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnHandleIntent :: Invoked.");
    
                await DoWork();
                await Task.Delay(TimeSpan.FromMinutes(2));
            }
            catch (Exception e)
            {
                Log.Debug(LogTag, $"GpsTrackerService.OnCreate :: Exception:{e.Message} Type:{e.GetType().Name}");
                GpsTrackerServiceUtils.SendExceptionToApplicationInsightsWakeLock(e, LogTag, _mobileServiceClient, this);
            }
            finally
            {
                WakefulBroadcastReceiver.CompleteWakefulIntent(intent);
                SendBroadcast(new Intent(this, typeof(GpsTrackerServceWakefulReceiver)));
                //var wakefulReceiverIntent = new Intent(this, typeof(GpsTrackerServceWakefulReceiver));
                //var pending = PendingIntent.GetBroadcast(this, 0, wakefulReceiverIntent, PendingIntentFlags.UpdateCurrent);
                //AlarmManager manager = (AlarmManager)GetSystemService(AlarmService);
                //manager.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 120 * 1000, pending);
            }
        }
    
    
        public async Task DoWork()
        {
            // long running code ...
            Log.Debug(LogTag, "GpsTrackerService.HandleTimerCallback :: Invoked.");
            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.HandleTimerCallback :: Invoked.");
    
    
        }
    }
    
    广播接收机

    [BroadcastReceiver(Enabled = true, Exported = true, Name = GpsConstants.GpsBroadcastReceiver, Label = "RestartServiceWhenStopped")]
    [IntentFilter(new[] {GpsConstants.GpsRestart})]
    public class GpsTrackerServiceBroadcastReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            try
            {
                MetricsManagerHelper.Instance.SendGenericMessageToApplicationInsights("Gps-Info", "OnReceive :: Gps Service broadcast message received. Restarting GPS Service...");
                context.StartService(new Intent(context, typeof(GpsTrackerService)));
             }
            catch (Exception e)
            {
                MetricsManagerHelper.Instance.SendExceptionToApplicationInsights(e);
            }
        }
    }
    
    [BroadcastReceiver]
    public class GpsTrackerServceWakefulReceiver : WakefulBroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var serviceIntent = new Intent(context, typeof(GpsTrackerIntentService));
            StartWakefulService(context, serviceIntent);
        }
    }
    
    在MainActivity.OnCreate中注册Broadcastreceiver

    [Service]
    public class GpsTrackerService : Service
    {
        private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerService).Name;
        private static readonly int NOTIFICATION_ID = 10000;
        private MobileServiceClient _mobileServiceClient;
    
        public TelephonyManager GetTelefonyManager()
        {
            return (Android.Telephony.TelephonyManager) GetSystemService(TelephonyService);
        }
    
        public bool IsRunningAsService { get; set; }
    
    
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(LogTag, "GpsTrackerService.OnStartCommand :: Service started. Timer instantiated.");
            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsights("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnStartCommand :: Service started.Timer instantiated.");
    
            Task.Run(async () =>
            {
                try
                {
                    await DoWork();
                    await Task.Delay(TimeSpan.FromMinutes(2));
                }
                catch (Exception e)
                {
                    Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.Message} Type:{e.GetType().Name}, Stacktrack:{e.StackTrace}");
                    if (e.InnerException != null)
                    {
                        Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.InnerException.Message} Type:{e.InnerException.GetType().Name}, Stacktrack:{e.InnerException.StackTrace}");
                    }
                    GpsTrackerServiceUtils.SendExceptionToApplicationInsights(e, LogTag, _mobileServiceClient, this);
                }
                finally
                {
                    // Restart Service
                    Intent broadcastIntent = new Intent(action: GpsConstants.GpsRestart);
                    SendBroadcast(broadcastIntent);
                }
    
            });
    
            return StartCommandResult.Sticky;
        }
    
          public override IBinder OnBind(Intent intent)
        {
            // This is a started service, not a bound service, so we just return null.
            return null;
        }
    }
    
     GpsTrackerServiceBroadcastReceiver = new GpsTrackerServiceBroadcastReceiver();
     RegisterReceiver(GpsTrackerServiceBroadcastReceiver, new IntentFilter(GpsConstants.GpsBroadcastReceiver));
    
    [Service]
    public class GpsTrackerIntentService : IntentService
    {
        private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerIntentService).Name;
        private static readonly int NOTIFICATION_ID = 10000;
        private MobileServiceClient _mobileServiceClient;
    
        public TelephonyManager GetTelefonyManager()
        {
            return (TelephonyManager) GetSystemService(TelephonyService);
        }
    
        protected override async void OnHandleIntent(Intent intent)
        {
            try
            {
                // perform task
                await Bootstrap();
    
                GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnHandleIntent :: Invoked.");
    
                await DoWork();
                await Task.Delay(TimeSpan.FromMinutes(2));
            }
            catch (Exception e)
            {
                Log.Debug(LogTag, $"GpsTrackerService.OnCreate :: Exception:{e.Message} Type:{e.GetType().Name}");
                GpsTrackerServiceUtils.SendExceptionToApplicationInsightsWakeLock(e, LogTag, _mobileServiceClient, this);
            }
            finally
            {
                WakefulBroadcastReceiver.CompleteWakefulIntent(intent);
                SendBroadcast(new Intent(this, typeof(GpsTrackerServceWakefulReceiver)));
                //var wakefulReceiverIntent = new Intent(this, typeof(GpsTrackerServceWakefulReceiver));
                //var pending = PendingIntent.GetBroadcast(this, 0, wakefulReceiverIntent, PendingIntentFlags.UpdateCurrent);
                //AlarmManager manager = (AlarmManager)GetSystemService(AlarmService);
                //manager.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 120 * 1000, pending);
            }
        }
    
    
        public async Task DoWork()
        {
            // long running code ...
            Log.Debug(LogTag, "GpsTrackerService.HandleTimerCallback :: Invoked.");
            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.HandleTimerCallback :: Invoked.");
    
    
        }
    }
    
    2.尝试

    服务

    [Service]
    public class GpsTrackerService : Service
    {
        private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerService).Name;
        private static readonly int NOTIFICATION_ID = 10000;
        private MobileServiceClient _mobileServiceClient;
    
        public TelephonyManager GetTelefonyManager()
        {
            return (Android.Telephony.TelephonyManager) GetSystemService(TelephonyService);
        }
    
        public bool IsRunningAsService { get; set; }
    
    
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(LogTag, "GpsTrackerService.OnStartCommand :: Service started. Timer instantiated.");
            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsights("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnStartCommand :: Service started.Timer instantiated.");
    
            Task.Run(async () =>
            {
                try
                {
                    await DoWork();
                    await Task.Delay(TimeSpan.FromMinutes(2));
                }
                catch (Exception e)
                {
                    Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.Message} Type:{e.GetType().Name}, Stacktrack:{e.StackTrace}");
                    if (e.InnerException != null)
                    {
                        Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.InnerException.Message} Type:{e.InnerException.GetType().Name}, Stacktrack:{e.InnerException.StackTrace}");
                    }
                    GpsTrackerServiceUtils.SendExceptionToApplicationInsights(e, LogTag, _mobileServiceClient, this);
                }
                finally
                {
                    // Restart Service
                    Intent broadcastIntent = new Intent(action: GpsConstants.GpsRestart);
                    SendBroadcast(broadcastIntent);
                }
    
            });
    
            return StartCommandResult.Sticky;
        }
    
          public override IBinder OnBind(Intent intent)
        {
            // This is a started service, not a bound service, so we just return null.
            return null;
        }
    }
    
     GpsTrackerServiceBroadcastReceiver = new GpsTrackerServiceBroadcastReceiver();
     RegisterReceiver(GpsTrackerServiceBroadcastReceiver, new IntentFilter(GpsConstants.GpsBroadcastReceiver));
    
    [Service]
    public class GpsTrackerIntentService : IntentService
    {
        private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerIntentService).Name;
        private static readonly int NOTIFICATION_ID = 10000;
        private MobileServiceClient _mobileServiceClient;
    
        public TelephonyManager GetTelefonyManager()
        {
            return (TelephonyManager) GetSystemService(TelephonyService);
        }
    
        protected override async void OnHandleIntent(Intent intent)
        {
            try
            {
                // perform task
                await Bootstrap();
    
                GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnHandleIntent :: Invoked.");
    
                await DoWork();
                await Task.Delay(TimeSpan.FromMinutes(2));
            }
            catch (Exception e)
            {
                Log.Debug(LogTag, $"GpsTrackerService.OnCreate :: Exception:{e.Message} Type:{e.GetType().Name}");
                GpsTrackerServiceUtils.SendExceptionToApplicationInsightsWakeLock(e, LogTag, _mobileServiceClient, this);
            }
            finally
            {
                WakefulBroadcastReceiver.CompleteWakefulIntent(intent);
                SendBroadcast(new Intent(this, typeof(GpsTrackerServceWakefulReceiver)));
                //var wakefulReceiverIntent = new Intent(this, typeof(GpsTrackerServceWakefulReceiver));
                //var pending = PendingIntent.GetBroadcast(this, 0, wakefulReceiverIntent, PendingIntentFlags.UpdateCurrent);
                //AlarmManager manager = (AlarmManager)GetSystemService(AlarmService);
                //manager.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 120 * 1000, pending);
            }
        }
    
    
        public async Task DoWork()
        {
            // long running code ...
            Log.Debug(LogTag, "GpsTrackerService.HandleTimerCallback :: Invoked.");
            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.HandleTimerCallback :: Invoked.");
    
    
        }
    }
    
    WakefulReceiver

    [BroadcastReceiver(Enabled = true, Exported = true, Name = GpsConstants.GpsBroadcastReceiver, Label = "RestartServiceWhenStopped")]
    [IntentFilter(new[] {GpsConstants.GpsRestart})]
    public class GpsTrackerServiceBroadcastReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            try
            {
                MetricsManagerHelper.Instance.SendGenericMessageToApplicationInsights("Gps-Info", "OnReceive :: Gps Service broadcast message received. Restarting GPS Service...");
                context.StartService(new Intent(context, typeof(GpsTrackerService)));
             }
            catch (Exception e)
            {
                MetricsManagerHelper.Instance.SendExceptionToApplicationInsights(e);
            }
        }
    }
    
    [BroadcastReceiver]
    public class GpsTrackerServceWakefulReceiver : WakefulBroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            var serviceIntent = new Intent(context, typeof(GpsTrackerIntentService));
            StartWakefulService(context, serviceIntent);
        }
    }
    
    AndroidManifest.xml

    添加了唤醒锁定权限

      <uses-permission android:name="android.permission.WAKE_LOCK"/>
      <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    
    
    
    我现在真的很绝望。希望有人能帮助我。 谢谢


    Eric

    没有回答,你也没有找到解决方案?