【问题标题】:How to bind to running android service?如何绑定到正在运行的android服务?
【发布时间】: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


【解决方案1】:

这是一个异步调用吗? 必须等待某事 完成了吗?

在您的 ServiceConnection 对象上调用 onServiceConnected() 之前,绑定尚未准备好。

【讨论】:

  • 发生这种情况的原因是什么?有什么方法可以确保在我的onResume() 之前发生这种情况?
  • @commonsware 有一个长期运行的服务,然后绑定服务,解除绑定,然后该服务继续运行,这是可能的还是很好的做法?
猜你喜欢
  • 2011-05-25
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
相关资源
最近更新 更多