2012-11-07 50 views
2

我遇到了问题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()方法中的日志(尽管应该一开始就没有约束力!)。

回答

4

有同样的问题,但意识到我的服务并没有真正开始。也许尝试添加“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);