我的应用程序使用由 BOOT_COMPLETE BroadcastReceiver 启动的服务,如下所示:
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
}
如果在我的应用程序的 Activity 中,我尝试像这样绑定(bind)到此服务:
getApplicationContext().bindService(new Intent(getApplicationContext(), MyService.class),
_serviceConnection, Context.BIND_AUTO_CREATE);
尽管第一个实例(由 BroadcastReceiver 创建)仍在运行,但创建了一个新的服务实例。我在服务的 onCreate() 方法中记录了进程 ID,第一个 服务在与 Activity 不同的进程中运行,第二个实例是在与 Activity 相同的进程中创建的。我尝试在 list 的服务元素中设置一个 android:process 参数(有前导 : 和没有),但结果保持不变。
如何绑定(bind)到在不同进程中运行的服务,而不是在运行 Activity 的进程中创建新实例?
最佳答案
我可以向你保证,事实并非如此。无论您启动或绑定(bind)多少次,特定服务组件的一个实例始终处于 Activity 状态。此外,服务只会在一个进程中运行。它不可能在不同的时间在不同的进程中运行。
关于android - 绑定(bind)到已由广播接收器启动的服务会创建新的服务实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6010751/