默认情况下,无论是通过startService还是bindService启动同一Application的Service组件,该Service组件都是运行在该Application的同一进程中。然而,很多时候我们希望该Service组件可以运行在不同的进程中,这样做的目的往往是为了让其与该Application拥有独立的运行环境,可以避免类似因为Service的crash导致Application也被crash的问题发生。
可以利用Service组件的“android:process”属性来实现这个功能。查看Android官方开发文档对“android:process”属性的说明:
If we want to make this service run in a remote process (instead of the standard one for its .apk), we can use android:process in its manifest tag to specify one:
<service android:name=".app.MessengerService"
android:process=":remote" />
Note that the name “remote” chosen here is arbitrary, and you can use other names if you want additional processes. The ‘:’ prefix appends the name to your package’s standard process name.
也就是说,在AndroidManifest.xml中注册该Service组件的时候,可以通过"android:process"属性来定义其运行的进程,如下所示,该组件将运行在一个名为"newService"的进程中。
<service
android:name="xxx"
android:process=":newService" //该Service会运行在名为"newService"的进程
</service>