ctn*_*213 2 android android-service
我试图将服务绑定到我的活动,并在执行这段代码后出于某种原因:
new Thread(new Runnable() {
public void run() {
httpdIntent = new Intent(MainActivity.this, HttpdService.class);
bindService(httpdIntent, mConnection, Context.BIND_AUTO_CREATE);
}
}).start();
Run Code Online (Sandbox Code Playgroud)
没有其他事情发生.没有例外,但onCreate方法不会像它应该的那样被调用.我可能误解了它是如何工作的但是我想在运行这个线程之后应该立即创建服务.这不正确吗?任何建议将不胜感激.
当服务绑定时,它将调用onBind()服务的方法,而不是onCreate().查看此图像,其中显示了绑定服务的生命周期(取自文档):

实际上,调用onCreate服务方法的唯一方法是使用该startService()方法调用它.根据这里的文件:
如果有人调用Context.startService(),那么系统将检索服务(创建它并在需要时调用其onCreate()方法),然后使用客户端提供的参数调用其onStartCommand(Intent,int,int)方法.
在任何情况下,如果您想要onCreate()调用该服务,您只需在绑定它之前启动该服务:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
bindService(startIntent, mConnection, Context.BIND_AUTO_CREATE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4657 次 |
| 最近记录: |