android - bindService 没有调用我的服务类的 onCreate 方法

标签 android android-service

在执行这段代码后,我正在尝试将服务绑定(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 ):

enter image description here

确实,调用服务的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/

相关文章:

android - 与现有 iOS 和 Android 应用程序中的嵌入式 (UI)Webviews 通信

java - 如何在android中使用retrofit获取Json响应中的数组数据?

java - Android开发者文档IntentService : Are we defining the same class twice?

android - 带有 IntentFilter 的 BroadcastReceiver for Intent.ACTION_PACKAGE_REPLACED 在服务中不工作

android - 如何在我的一个 viewpager 页面中访问我的按钮?

android - 无法访问相机

android - 无法注册 NSD 服务

android - 针对电池消耗优化服务

android - 使用不同状态下的两个图像切换按钮

android - 通知操作不打开服务