问题描述
首先,我有一个lib库,库里面定义了以个Service:
<application android:allowBackup='true' android:label='@string/app_name' android:supportsRtl='true'> <serviceandroid:name='.SharedService'android:process='com.lib.aidl.SharedService'android:enabled='true'android:exported='true'> </service></application>
现在,加入有两个app都引入了这个库,然后在各自的代码里都调用了:
startService(new Intent(context, SharedService.class))
我现在想的是系统中应该只有一个SharedService的实例,在进程com.lib.aidl.SharedService中。
但是实际情况是有两个SharedService的实例,它们都在进程名为com.lib.aidl.SharedService的进程中,但是进程id是不一样的。这是为什么?
我现在想让系统中仅出现一个SharedService的实例,当第二次调用startService时回调onStartCommand方法,这个可以做到么?
问题解答
回答1:将
android:process='com.lib.aidl.SharedService'
替换成
android:process=':com.lib.aidl.SharedService'
试试
注意,加了个 ’:’
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 <application> 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.