Android 服务:进程与非进程
将服务放在单独的进程中或将其保留在应用程序的主进程中之间有什么实际区别?每个场景的用途是什么?
What are the practical differences between putting a service in a separate process or keeping it in the app's main process? What would each scenario be used for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当服务在主进程中运行时,如果您的应用程序因某种原因崩溃,它将停止。对于某些可以从不同应用程序使用的服务或应独立于主应用程序运行的服务,将服务放入其自己的进程中是合理的。
When a service is running in the main process it will be stopped in case your application crashes for whatever reason. Put a service into it's own process is reasonable for some services which can be used from different applications or services which should run independently from your main app.
我认为将服务放入另一个进程中的唯一原因是
但是,如果您创建一个好的应用程序并使用好的编程,您就不应该遇到这些问题。通过将您的服务放在单独的进程中,它会导致 SharedPreferences 和并发数据库访问等问题......我建议不要这样做。
更不用说...另一个进程意味着另一个DVM。与在一个 DVM 中运行相比,这会占用更多资源,并且速度会变慢。
The only reasons I see for putting a service in another process is
However if you create a good application and use good programming you should not run into either of these issues. By having your service in a separate process it causes trouble with things like SharedPreferences and concurrent DB access... I would recommend not doing it.
Not to mention... another process means another DVM. This will take more resources than running in one DVM and slow things down.
此外,将服务放在另一个进程中会使您对静态变量的更改对于主进程不可见。当你为一个变量分配一些值时,你可以得到这样的情况,并且它没有改变!为了这个问题我花了一整天的时间!
Also putting service in another process makes your changes of static variables invisible for main process. You can get situation, when you assign a variable with some value, and it is not changed!! I spent whole day for this issue!
以下引用自 Android 开发人员网站。
Jake 指出,您可以通过清单控制正在运行的进程的名称。但以下来自文档的发现:
这很有趣,这里所说的是:
但无论如何,如果您需要将 Service 暴露给其他应用程序,例如,您需要向其他应用程序提供内容(如电话簿),则将 Service 设置为在不同进程中运行就是原因。
Following is a quote from Android Developer's web site.
Jake points out that you can, thru manifest, control the Name of the process it is running. But following findings from Documentatioin:
This is interesting, what is said Here is:
But anyway, if you need Service to be exposed to other applications, for example, you need to provide content (like phonebook) to other applications, setting service to run in different process is the reason.
使用服务的进程属性会被清单解析器拒绝,因此这是相当误导的!
Using the process attribute of a service is rejected by the manifest parser so it is rather misleading!