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

标签 c# java android .net xamarin

更新: 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 声明中添加“:”在其自己的进程中运行该服务。

关于c# - 应用程序在后台关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21859843/

相关文章:

android - 同步 build.grandle 时出现 webrtc native API 'vectorDrawable' 和 'Task' 错误

c# - 如何使用 C# 查询 NTP 服务器?

c# - 将 Entity Framework 与存档数据库一起使用

java - Netty 与 Apache MINA

java - 自动缩放的 Android 2x2 行图像

android - 将单选按钮排列在文本正下方,并完美地位于所有 Android 设备的中心

android - 使用 wmiobject 通过 powershell 在 MTP 模式下浏览 android 设备的文件系统

c# - Action<Action> 是什么意思?

c# - 将 Entity Framework 升级到 6.1 - 索引已存在错误

java - 无法在java中使用此正则表达式提取字符串