我遇到了问题bindService()
。我试图在构造函数中进行绑定,提供一个包含两个可分派额外项的Intent。在onResume()
中调用该构造函数,并且该服务在其onBind()
方法中分析了这两个附加项,并且可能会返回null
作为解析的结果。Android bindService不工作
当我第一次运行应用程序(通过在Eclipse中运行)绑定(预计)被服务拒绝:服务的onBind()
方法被调用并返回null
。但是,应用程序方面的bindService()
方法返回true
(不应该,因为绑定没有经过!)。
当我尝试以下操作时,会出现更多问题:我按HOME按钮并再次启动应用程序(因此它的onResume()
再次运行,应用程序尝试再次绑定到该服务)。这一次服务的onBind()
似乎并没有运行!但该应用程序的bindService()
仍然会返回true
!
下面是一些示例代码,应该可以帮助您理解我的问题。
应用端:
// activity's onResume()
@Override
public void onResume() {
super.onResume();
var = new Constructor(this);
}
// the constructor
public Constructor(Context context) {
final Intent bindIntent = new Intent("test");
bindIntent.putExtra("extra1",extra_A);
bindIntent.putExtra("extra2",extra_B);
isBound = context.bindService(bindIntent, connection, Context.BIND_ADJUST_WITH_ACTIVITY);
log("tried to bind... isBound="+isBound);
}
服务端:
private MyAIDLService service = null;
@Override
public void onCreate() {
service = new MyAIDLService(getContentResolver());
}
@Override
public IBinder onBind(final Intent intent) {
log("onBind() called");
if (intent.getAction().equals("test") {
ExtraObj extra_A = intent.getParcelableExtra("extra1");
ExtraObj extra_B = intent.getParcelableExtra("extra2");
if (parse(extra_A,extra_B))
return service;
else {
log("rejected binding");
return null;
}
}
}
的ServiceConnection
我使用存在以下onServiceConnected()
方法:
@Override
public void onServiceConnected(final ComponentName name, final IBinder service) {
log("onServiceConnected(): successfully connected to the service!");
this.service = MyAIDLService.asInterface(service);
}
所以,我从来没有去看看“成功连接到服务!”登录。我第一次运行应用程序(通过Eclipse),我得到了“拒绝绑定”日志以及“isBound = true”,但从那里我只得到“isBound = true”,“拒绝绑定”doesn再也不会出现了。
我怀疑这可能与Android认识到即使在强制拒绝时有成功绑定的可能性有关。理想情况下,我也可以强制“解除绑定”,但这是不可能的:我怀疑这是因为,当我杀死应用程序时,我收到了位于服务的onUnbind()
方法中的日志(尽管应该一开始就没有约束力!)。