Long 运行 在 FileObserver 的 onEvent 内部操作

Long running operation inside onEvent of FileObserver

我有一个包含 FileObserver 实例的 activity。我开始在 onCreate 中观看并在 activity 的 onDestroy 中停止观看。那么如果 onEvent 正在执行某些操作并且 activity 被销毁(用户按下后退按钮)会发生什么?我的 onEvent 是否继续完成它正在做的事情?基本上我想知道 onEvent 是应该启动一个服务还是自己处理它的业务。

除非应用程序停止,否则您的 onEvent 中的代码将继续 运行。

FileObserver.onEvent documentation

This method is invoked on a special FileObserver thread. It runs independently of any threads, so take care to use appropriate synchronization! Consider using post(Runnable) to shift event handling work to the main thread to avoid concurrency problems.

所以您唯一需要关心的是您在 onEvent 中到底在做什么。例如,如果您在 onEvent 方法中更新 UI 或与 Activity / Fragment 交互,那么如果 Activity 消失,这可能会导致崩溃。

考虑到这一点,服务肯定会增加应用程序在您执行工作时不会终止的可能性。

Service documentation

The Android system will force-stop a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, then it's less likely to be killed, and if the service is declared to run in the foreground (discussed later), then it will almost never be killed. Otherwise, if the service was started and is long-running, then the system will lower its position in the list of background tasks over time and the service will become highly susceptible to killing—if your service is started, then you must design it to gracefully handle restarts by the system. If the system kills your service, it restarts it as soon as resources become available again...

所以底线是服务更有可能使您的应用程序保持活动状态。如果您调用 startForeground,则事件更有可能发生,但在这种情况下,您需要愿意向用户显示通知。

Does my onEvent continue to finish what it was doing?

至少是短暂的,是的。 FileObserver 与特定组件的生命周期无关,例如 Activity.

但是,一旦您的应用程序不再在前台运行,您的进程就可以随时终止,以便为其他应用程序释放系统 RAM。默认情况下,Android 不会关注您的 FileObserver 及其 onEvent() 处理。

如果您希望工作快速进行——比如,在一秒钟内——您应该能够将其保持在原位。

但是,如果您正在做的工作种类更多,我会考虑让服务来完成这项工作。根据我们的 ,虽然 FileObserver 不应该在 IntentService 中,但由 FileObserver 触发的工作可以。 onEvent() 会调用 startService() 告诉服务去做这项工作。服务是向 OS 发出的信号,表明您正在代表用户积极开展工作,因此您的流程更有可能停留更长时间。