Android 绑定到BroadcastReceiver启动的allready服务将创建新的服务实例

Android 绑定到BroadcastReceiver启动的allready服务将创建新的服务实例,android,service,process,ipc,broadcastreceiver,Android,Service,Process,Ipc,Broadcastreceiver,我的应用程序使用由引导接收器启动的服务,如下所示: public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, MyService.class)); } getApplicationContext().bindService(new Intent(getApplicationContext(), MyService.class), _servi

我的应用程序使用由引导接收器启动的服务,如下所示:

public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context, MyService.class));
}
getApplicationContext().bindService(new Intent(getApplicationContext(), MyService.class), 
    _serviceConnection, Context.BIND_AUTO_CREATE);
如果在我的应用程序中的活动中,我尝试像这样绑定到此服务:

public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context, MyService.class));
}
getApplicationContext().bindService(new Intent(getApplicationContext(), MyService.class), 
    _serviceConnection, Context.BIND_AUTO_CREATE);
创建了服务的新实例,尽管第一个实例(由BroadcastReceiver创建)仍在运行。我将进程ID记录在服务的onCreate()方法中,第一个 服务在与活动不同的进程中运行,第二个实例在与活动相同的进程中创建。我尝试在清单的service元素中设置一个android:process参数(带前导:和不带前导):但结果保持不变


如何绑定到在不同流程中运行的服务,而不是在活动运行的流程中创建新实例?

我可以向您保证,它不会。一次只有一个特定服务组件的实例处于活动状态,无论您启动或绑定它多少次。此外,该服务将仅在一个进程中运行。它无法在不同的时间在不同的进程中运行。

为什么广播接收器和活动在不同的进程中运行?这有必要吗?您需要AIDL和进程间通信来完成您想要的任务。@bigstones:广播接收器不需要在不同的进程中运行。显然,这只是安卓默认设置的方式。如何使广播接收器和我的主要活动在同一进程中运行?默认情况下,它们应该在同一进程中运行,AFAIK。你能发布清单吗?@bigstones:我刚刚更改了我服务的onBind()方法,以返回一个aidl活页夹,而不是我以前使用的Messenger。不幸的是,结果仍然是一样的。@bigstones:manifest(有点模糊)。