How to create an Android Activity and Service that

2020-01-28 08:52发布

I have an Android app that consists of an activity and a service. Currently they both exist in the same process and use the same heap but I want have to separate process/heap for the service. Ie. I want the service to be completely independent of the activity so that if the activity crashes it won't affect the service. I do, however, want them to be installable as a single application. Is this possible?

2条回答
一纸荒年 Trace。
2楼-- · 2020-01-28 09:07

Definitely possible. See the process attribute for service in AndroidManifest.xml

http://developer.android.com/guide/topics/manifest/service-element.html

To quote:

The name of the process where the service is to run. Normally, all components of an application run in the default process created for the application. It has the same name as the application package. The element's process attribute can set a different default for all components. But component can override the default with its own process attribute, allowing you to spread your application across multiple processes.

If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process. If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.

查看更多
够拽才男人
3楼-- · 2020-01-28 09:30

IPC for services is IMHO only required if the service should be consumed by other applications.

Running a service in its own process has the small advantages that the garbage collector for the service does not affect your application and that the memory footprint of the service is a bit smaller if it runs alone.

If consumption of the service by other applications is not a requirement for you, prefer a local service. Alternatively you can still run the service in its own process and use different communication with your application, e.g. via a broadcast receiver. I tried to describe the different approaches in my Android service tutorial under the following link: Activity and service communication.

查看更多
登录 后发表回答