我的Android应用程序通过前台服务启动并保持TCP连接。活动使用StartService()
来启动服务。同时,该服务在自己的进程中启动。
以下是服务的OnStartCommand
:
// Code is in C# using Xamarin but regular Java/Android answers are acceptable
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
{
base.OnStartCommand (intent, flags, startId);
...
var ongoingNotification = new Notification (Resource.Drawable.icon, "Service running");
var pendingIntent = PendingIntent.GetActivity (this, 0, new Intent (this, typeof(MainActivity)), 0);
ongoingNotification.SetLatestEventInfo (this, "Service", "The service is running.", pendingIntent);
StartForeground ((int)NotificationFlags.ForegroundService, ongoingNotification);
return StartCommandResult.RedeliverIntent;
}
当手机屏幕开启时,无论我的应用程序是否打开或未打开活动,连接都很好。然而,在我关闭屏幕不到30秒后,我总是会失去TCP连接。我的应用程序会自动重新连接,因此我会恢复连接,但在屏幕关闭时它将持续断开连接。我重新打开屏幕后,它就没问题了,即使我的应用程序中没有打开任何活动。
这可能与Android生命周期有关,但我不知道原因。根据我写入手机文本文件的调试消息(当IDE的调试器附加时,问题不会发生),服务似乎正在按照预期运行,但连接却不稳定。
我还测试了开发者选项中选择“不保留活动”和不选两种情况,但结果没有改变。所以至少与Activity Lifecycle无关。
为什么Android在屏幕关闭时会丢失我的TCP连接?