Android 服务中的文件操作
File operations in Android service
Android 服务可能随时被操作系统杀死。没有像 onDestroy()
这样可以信赖的保证生命周期调用。我必须实现一项服务,在后台执行大量 运行 长任务和一堆文件操作。所以我的问题是:
- 在任何服务中这样做通常是个好主意吗?当进程被终止时,打开的文件句柄会发生什么?
- 有没有像使用前台服务这样的首选方法?
我想我不会是第一个拥有这种 problem/question 的人,但我在 Google 或 SO 上找不到任何东西。提前致谢。
Android services might get killed by the operating system at any possible time.
更准确地说,Android 应用程序 进程 可能随时被操作系统杀死。
There are no guaranteed lifecycle calls like onDestroy() you can rely on.
正确。 onDestroy()
被调用的可能性很大,但不保证。
I have to implement a service doing a lot of long running tasks and a bunch of file operations in the background.
几乎所有大于 "hello, world" 的软件都符合该描述。
Is it generally a good idea to do that in any kind of service?
您没有太多选择。从 UI 的角度来看,服务可以帮助您在进程不再处于前台时保持运行。如果您不使用服务,您的进程生命周期可能只有几分钟,甚至更少。对于服务,您的进程生命周期可能是几个小时,尽管这在很大程度上取决于设备(例如,系统 RAM 的数量)和用户(例如,用户有多忙以及有多少其他应用程序想要做后台工作)。
What happens with an open file handle when the process gets killed?
如果您尝试在进程终止点左右向文件写入内容,则任何尚未移交给 OS 的字节(例如,缓冲在 Java 中)将不会在文件。
Is there a preferred way to achieve this
我不知道 "this" 是什么。
like using a foreground service?
使用前台服务主要有三种模式:
简单交易。例如,K9 Mail 在检查新邮件时似乎使用前台服务,但仅在 window.
期间
用户控制的操作。这是前台服务的常规用例。例如音乐播放器,通常会实现音乐播放的前台服务。
"I am going to try to live forever" 种服务。这不是特别实用,因为前台服务不会永远存在。用户也会对前台服务感到恼火,因为他们不明白他们得到了什么作为系统消耗和始终可见的通知图标的权衡。
这些模式是否适合您的项目是您需要自己确定的。
Android 服务可能随时被操作系统杀死。没有像 onDestroy()
这样可以信赖的保证生命周期调用。我必须实现一项服务,在后台执行大量 运行 长任务和一堆文件操作。所以我的问题是:
- 在任何服务中这样做通常是个好主意吗?当进程被终止时,打开的文件句柄会发生什么?
- 有没有像使用前台服务这样的首选方法?
我想我不会是第一个拥有这种 problem/question 的人,但我在 Google 或 SO 上找不到任何东西。提前致谢。
Android services might get killed by the operating system at any possible time.
更准确地说,Android 应用程序 进程 可能随时被操作系统杀死。
There are no guaranteed lifecycle calls like onDestroy() you can rely on.
正确。 onDestroy()
被调用的可能性很大,但不保证。
I have to implement a service doing a lot of long running tasks and a bunch of file operations in the background.
几乎所有大于 "hello, world" 的软件都符合该描述。
Is it generally a good idea to do that in any kind of service?
您没有太多选择。从 UI 的角度来看,服务可以帮助您在进程不再处于前台时保持运行。如果您不使用服务,您的进程生命周期可能只有几分钟,甚至更少。对于服务,您的进程生命周期可能是几个小时,尽管这在很大程度上取决于设备(例如,系统 RAM 的数量)和用户(例如,用户有多忙以及有多少其他应用程序想要做后台工作)。
What happens with an open file handle when the process gets killed?
如果您尝试在进程终止点左右向文件写入内容,则任何尚未移交给 OS 的字节(例如,缓冲在 Java 中)将不会在文件。
Is there a preferred way to achieve this
我不知道 "this" 是什么。
like using a foreground service?
使用前台服务主要有三种模式:
简单交易。例如,K9 Mail 在检查新邮件时似乎使用前台服务,但仅在 window.
期间
用户控制的操作。这是前台服务的常规用例。例如音乐播放器,通常会实现音乐播放的前台服务。
"I am going to try to live forever" 种服务。这不是特别实用,因为前台服务不会永远存在。用户也会对前台服务感到恼火,因为他们不明白他们得到了什么作为系统消耗和始终可见的通知图标的权衡。
这些模式是否适合您的项目是您需要自己确定的。