可运行与服务;用用例解释寿命

Runnable vs Service; Lifespan explained with use-cases

据我了解 - Runnable 和 Service 都旨在 运行 后台代码。我的代码结构是这样的:

  1. BaseManager.class 作为单例实现,使用 BaseManager.getInstance() 将在应用程序中 return 单实例。此外,首次初始化时,它会自动创建 SmallerAndCompletelyDifferentManager.class - 具有依赖性。

  2. SmallerAndCompletelyDifferentManager.class - 创建一个每 2 秒 运行s 的 Runnable。

现在,我有两个场景:

场景 A: 我首先在 Activity 中创建初始化 BaseManager.class 并在需要的任何地方使用它。 SmallerAndCompletelyDifferentManager.class 运行 里面的 Runnable 没问题,但据我所知,它附加到 Activity - 如果 Activity 死了,我买不起的 Runnable 也会死。

场景 B: 我创建了一个前台服务并初始化了 BaseManager.class。这是否意味着现在 Runnable 将按预期工作 - 即使应用程序在后台并且 Activity 已被销毁?

我做对了吗?总体计划是不惜一切代价确保Runnable在后台存活。

As I understand - both Runnable and Service are intended to run piece of code in background.

更具体地说,Service 在主线程上运行。如果您计划在服务中进行 CPU 密集型工作,则您有责任将工作放在单独的线程上。您可以将它放在 RunnableThread 中。

Am I getting this right or no? The overall plan is to make sure that Runnable survives in background at all costs.

方案 B 可行,但我的建议是将您的 BaseManager 修改为服务 class。

As I understand - both Runnable and Service are intended to run piece of code in background

这是不正确的。

Service 是一个可以在后台执行长运行ning 操作的应用程序组件。这里的背景意味着当用户与应用程序交互时,或者当用户切换到另一个应用程序时,你在幕后(或后台)做一些事情。

Runnable是一个可以运行的代码块,所以它的名字叫"Runnable",意思是可以run/execute。 Runnable 接口 应该 由任何 class 实现,其实例旨在由线程执行。

在Android中有两种线程,第一种是main/UI线程,另一种是后台线程。这里的背景意味着当你在一个线程而不是 main/UI 线程中做某事时。

回到你的案例

在场景 1 中: Activity 创建 Runnable 并保留对它的引用。当你销毁activity时(按返回键或调用finish()方法),activity会被销毁,运行nable会被释放。

在场景 2 中:前台服务创建 Runnable 并保留对它的引用。当你销毁 activity 或切换到另一个应用程序时,该服务仍然存在(并且 运行nable 也是如此)直到你通过调用(stopSelft()stopService() 方法)终止服务.因为在使用前台服务时,它会告诉系统该应用正在做一些重要的事情,不应该被杀死。