IT源码网

c#之应用程序在后台关闭

mfryf 2025年05月04日 程序员 26 0

更新: I've changed some things and better clarified my question here.

这个问题可以结束了。

<小时 />

快速说明:我使用 Xamarin 在 C# 中进行编码,但任何适用于常规 Java 和 Android 的解决方案都应该适用,因此如果您的响应不是特定于 C# 或 Xamarin,请不要担心。

我遇到一个问题,当屏幕关闭时,我的 Android 应用程序会被关闭,而且通常会在一分钟之内关闭。当应用程序打开时它会继续运行,所以也许它与android在不使用时处理我的应用程序的方式有关。不过,当我在 IDE 中调试应用程序时,这种情况不会发生,因为这可能会使应用程序保持 Activity 状态,所以我没有从中得到任何帮助。

该应用程序由一些 Activity 和一项服务组成。该服务使用 TCP 连接发送和接收数据。当应用程序打开时,它会启动登录 Activity 。然后,当您登录时,它会完成该 Activity 并打开主 Activity 。 Main Activity 在 OnResume 中使用 StartService (new Intent (this, typeof(MainService))); 启动 Service。

该服务是前台服务。

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; 
}  

应用程序关闭时运行的部分是主 Activity 和服务。

当我尝试重新打开应用程序时,它似乎尝试重新打开主 Activity ,但随后失败并关闭。然后,当我尝试第二次重新打开应用程序时,它会将应用程序打开回登录 Activity 。

“服务正在运行”通知始终保留在通知栏中,尽管它在应用程序关闭时丢失了 tcp 连接。这不好,因为服务需要长时间正常工作。

请您参考如下方法:

确保您通过startService 而不仅仅是bindService 启动服务。如果您需要绑定(bind)服务,也可以调用 startService ,这样它的运行时间就比绑定(bind)到它的服务运行的时间长。您已经提到您正在将其作为前台服务运行,这很好。最后,如果这些都不能解决您的问题,请通过在服务的 list 声明中添加“:”在其自己的进程中运行该服务。


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!