首页 > 解决方案 > Adding function to foreground service lifecycle methods can create an issue? Is this best practise?

问题描述

I created a timer app. So it's counting time basically and I'm saving the time to room when service close in OnDestroy scope. Is it best practise? Or is there any case that call the lifecycle methods without at user request?

标签: androidkotlinandroid-serviceandroid-lifecycle

解决方案


请注意,上述方法效率高/高性能。
这种方法正在消耗宝贵的Android 系统资源,因为当用户导航到另一个应用程序或用户接到电话时,计时的计时器仍在后台运行。

此应用程序可以运行,但 Android 操作系统会在需要更多内存时首先终止此应用程序会话。
这将导致不一致的用户体验和 Play 商店的低评分。

本案例的解决方案是研究实现Activity Lifecycle回调。

onPause()计时器应该在被调用而不是 on 时立即停止onDestroy()

请参考上面的链接并相应地实现所需的回调。这样,您将创建一个高性能且内存友好的应用程序。


推荐阅读