在执行这段代码后,我正在尝试将服务绑定(bind)到我的 Activity 和某些原因:
new Thread(new Runnable() {
public void run() {
httpdIntent = new Intent(MainActivity.this, HttpdService.class);
bindService(httpdIntent, mConnection, Context.BIND_AUTO_CREATE);
}
}).start();
没有其他事情发生。没有异常(exception),但没有像预期的那样调用 onCreate 方法。我可能误解了它是如何工作的,但我认为在这个线程运行之后应该立即创建服务。这不对吗?任何建议将不胜感激。
最佳答案
服务绑定(bind)时,会调用服务的onBind()
方法,而不是onCreate()
。查看这张显示绑定(bind)服务生命周期的图片(取自 docs ):
确实,调用服务的onCreate
方法的唯一方法是使用startService()
方法调用它。根据文档 here :
If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client.
在任何情况下,如果您想要调用onCreate()
服务,您只需在绑定(bind)之前启动该服务即可:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
bindService(startIntent, mConnection, Context.BIND_AUTO_CREATE);
关于android - bindService 没有调用我的服务类的 onCreate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17757651/