如果我每 120 秒发送一次 GPS(纬度/经度),我必须实施一项服务。到我的 REST 后端。
我的问题是屏幕关闭时服务似乎停止工作。
- 尝试使用 StartedService 和 BroadcastReceiver
- 尝试使用 IntentService 和 WakefulBroadcastReceiver
1. Attempt 例如适用于 SAMSUNG Galaxy X COVER,但不适用于 HUAWEI P9 Lite。尽管我关闭了华为手机中的省电模式(Power Apps)。所以当屏幕关闭时我的应用程序会继续运行。例如 10 分钟后,我在华为手机上打开屏幕并在运行服务中看到服务正在运行(经过的秒数),因此我可以验证服务没有关闭。
2. 屏幕关闭时尝试在没有手机的情况下工作。
当屏幕打开(无睡眠)时,这两种尝试都正常工作。
注意:为简洁起见,我删除了不相关方法的代码(获取/传输 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;
}
}
广播接收器
[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);
}
}
}
在 MainActivity.OnCreate 中注册 Broadcastreceiver
GpsTrackerServiceBroadcastReceiver = new GpsTrackerServiceBroadcastReceiver();
RegisterReceiver(GpsTrackerServiceBroadcastReceiver, new IntentFilter(GpsConstants.GpsBroadcastReceiver));
2.尝试
服务
[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]
public class GpsTrackerServceWakefulReceiver : WakefulBroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var serviceIntent = new Intent(context, typeof(GpsTrackerIntentService));
StartWakefulService(context, serviceIntent);
}
}
AndroidManifest.xml
添加了 WAKE_LOCK 权限
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
我现在真的很绝望。希望可以有人帮帮我。谢谢
埃里克