【发布时间】:2010-07-28 23:03:07
【问题描述】:
我希望这更多的是代码问题,我希望有人可以帮助追查问题。
我还有其他使用 startService() 启动服务的代码,我可以验证服务是否已在调试器点击 DecoderService 的 onCreate() 函数时启动。
但是,bindService 永远不会绑定到正在运行的服务。这是一个异步调用,我必须等待某些事情完成吗?
public class ResultsActivity extends Activity {
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Intent decoderIntent = new Intent(this,DecoderService.class);
_isBound = bindService(decoderIntent,mConnection,Context.BIND_AUTO_CREATE);
_textView.start(_mBoundService);
}
private boolean _isBound = false;
private DecoderService _mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
_mBoundService = ((DecoderService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className)
_mBoundService = null;
}
};
}
public class DecoderService extends Service {
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
_numCompleted = 5;
_numTotal = 100;
}
protected int _numCompleted = 0;
protected int _numTotal = 0;
public void onCreate() {
onHandleIntent(null);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
DecoderService _ref = null;
public LocalBinder()
{
_ref = DecoderService.this;
}
DecoderService getService() {
return DecoderService.this;
}
}
}
【问题讨论】:
-
我只能告诉你 bindService() 有点异步。我试图在 onCreate 中调用它,然后稍后在 oncreate 中使用它,我得到了空指针异常。似乎直到 onCreate 完成后的某个时间它才真正被绑定。你怎么知道它永远不会绑定到服务?您可以在实际使用该服务的地方发布更多代码吗?
-
我的活动在 Tab 小部件中运行,显然在这种情况下,您必须传入 getApplicationContext(),而不是本地上下文。
标签: android service android-activity