在 Android 中保持服务器连接

Retaining server connection in Android

我的 Android 应用程序目前面临一些架构问题,而且我很难找到解决这些问题的 "Android way"。

该应用程序只是网络服务器的客户端。该应用程序需要连接到 Web 服务器,这可以通过几种不同的协议来完成,这需要花费很多时间来设置。

该应用程序允许 Android 处理设备旋转,并且 NOT 应用程序在旋转设备时重新连接到服务器是可以的。

这与应用程序中的其他类似问题密切相关,所以我想回答我的一些问题。

欢迎回答部分或全部问题!谢谢

Is a Singleton object retained after Orientation Changes? After switching from one activity to another? After multitasking away from the app to another? And for how long?

单例对象保留在内存中,直到其进程处于活动状态。当用户关闭 phone 或打开另一个消耗大量资源的应用程序时,它可能会被杀死。 但是在配置更改和活动切换时,单例保持不变。您可以覆盖您的应用程序 class 并在那里创建您的单例对象。

Are objects stored in the Application class retained during an orientation change?

否,应用程序 class 不会在应用程序的整个生命周期中保留。

If I have a service in my Android application (Lets say that it runs for 24/7), is the Application object alive 24/7 ? (I ask this question because I want to have the server connection singletons in the Application object.)

当系统需要更多资源时,系统也可能会重新启动服务。但是您可以使用 START_STICKY flag and it will be restarted by a system. But you can start service with startForeground 命令启动服务,并且它重新启动的机会几乎为零。但是那样的话,您需要在服务 运行 时显示特殊通知。例如,作为音乐应用程序。

Can you store your own objects in the Context or Application Context? What is the difference? Could this be used in some way for server connection? Or when is it supposed to be used?

抱歉,我不知道。当然,您可以将对象存储在您的应用程序实例中 class,但它们也会随应用程序一起保留。

我建议您使用一项服务(我在我的申请中这样做)。如果您的应用程序通常要显​​示有关您的连接的通知,您肯定可以使用 startForeground()。如果没有,您可以将服务作为单独的进程启动(使用 AndroidManifest.xml 中的 android:process 选项)。但是你需要小心地在应用程序和服务之间发送数据。如果这两种变体都不适合您 - 使用简单的服务。具有服务的应用程序具有更高的实时优先级。