我和bindService()有点问题。我正尝试在一个构造函数中进行绑定,提供一个包含两个可解析额外内容的Intent。构造函数在onResume()中被调用,服务在其onBind()方法中解析这两个额外参数,并可能返回null作为解析的结果。
当我第一次运行应用程序时(通过在Eclipse中运行),绑定(意外地)被服务拒绝:调用服务的onBind()方法并返回null。但是,在应用程序端,bindService()方法返回true (它不应该返回,因为绑定没有通过!)。
当我尝试以下操作时,这会变得更有问题:我按下主页按钮,然后再次启动应用程序(这样它的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)时,我得到了"rejected binding“日志和"isBound=true",但从那以后我只得到了"isBound=true","rejected binding”再也不会出现了。
我怀疑这可能与Android认识到有一个成功的绑定,即使我强迫拒绝的可能性有关。理想情况下,我也可以强制“解除绑定”,但这是不可能的:我怀疑这是因为,当我终止应用程序时,我会得到一个位于服务的onUnbind()方法中的日志(即使一开始就没有绑定!)。
发布于 2013-03-20 04:48:23
有相同的问题,但意识到我的服务实际上并没有启动。也许可以尝试将"Context.BIND_AUTO_CREATE“添加到标志中,这将导致创建并启动服务。我不相信Context.BIND_ADJUST_WITH_ACTIVITY会启动它,所以onServiceConnected可能不会被调用(即使bindService()调用返回true,它也不适合我):
isBound = context.bindService(bindIntent, connection,
Context.BIND_ADJUST_WITH_ACTIVITY | Context.BIND_AUTO_CREATE);https://stackoverflow.com/questions/13273332
复制相似问题