Android 从已绑定的服务返回不同的绑定器
我有一个服务已经通过AIDL被外部应用程序绑定 但是,有些服务请求需要启动活动。 由于我无法从服务内部调用startActivityForResult,因此我决定将本地活动也绑定到该服务 伪代码如下所示:Android 从已绑定的服务返回不同的绑定器,android,service,ipc,aidl,android-binder,Android,Service,Ipc,Aidl,Android Binder,我有一个服务已经通过AIDL被外部应用程序绑定 但是,有些服务请求需要启动活动。 由于我无法从服务内部调用startActivityForResult,因此我决定将本地活动也绑定到该服务 伪代码如下所示: class MyService extends Service{ public IBinder onBind(Intent intent){ if (intent.hasExtra("LocalBindingRequest")){ return
class MyService extends Service{
public IBinder onBind(Intent intent){
if (intent.hasExtra("LocalBindingRequest")){
return getLocalBinder();
else {
return getAidlBinder();
}
}
}
class ExternalApp extends Activity{
void someFunc(){
Intent i = new Intent(new ComponentName("com.my.pkg", "com.my.pkg.MyService");
bindService(i, myServiceConnection, Context.BIND_AUTO_CREATE);
}
}
class InternalApp extends Activity{
MyService mService;
void someFunc(){
Intent i = new Intent(new ComponentName("com.my.pkg", "com.my.pkg.MyService")
.putExtra("LocalBindingRequest", true);
bindService(i, myServiceConnection, Context.BIND_AUTO_CREATE);
}
public void onServiceConnected(ComponentName cn, IBinder service){
InternalBinder ib = (LocalBinder)service;
mService = ib.getService();
}
}
流程是这样的:
ExternalApp绑定到AidlBinder
ExternalApp调用需要服务启动活动的函数
服务启动活动
内部活动试图绑定
在onBind或onServiceConnected中,我在未命中断点的情况下出现异常
java.lan.ClassCastException:无法将AidlService强制转换为InternalBinder
服务不可能返回不同的活页夹吗
如果没有,我能做什么,将结果传播回已经绑定的MyService?好的,我应该已经阅读了onBindIntent中的文档 意图:用于绑定到此服务的意图,如 Context.bindService。请注意,包含在 在这一点上的意图将不会在这里看到 这就是为什么我得到了Aidl服务。解决办法是:
class InternalApp extends Activity{
MyService mService;
void someFunc(){
Intent i = new Intent(new ComponentName("com.my.pkg", "com.my.pkg.MyService");
i.setAction("LocalBindingRequest");
bindService(i, myServiceConnection, Context.BIND_AUTO_CREATE);
}
public void onServiceConnected(ComponentName cn, IBinder service){
InternalBinder ib = (LocalBinder)service;
mService = ib.getService();
}
}
class MyService extends Service{
public IBinder onBind(Intent intent){
if ("LocalBindingRequest".equals(intent.getAction()){
return getLocalBinder();
else {
return getAidlBinder();
}
}
}
我们可以为每个绑定请求提供单独的绑定