Android在活动中的onCreate启动服务问题活动中、问题、Android、onCreate

2023-09-12 05:55:09 作者:我走过最长的路是你的套路

我试图启动一个服务,并绑定到我的活动的的onCreate()方法的服务。当我尝试()事后打电话从服务功能如 commSessionManagerService.startCommandUpperM,一个 NullPointerException异常出现。下面是我用来启动该服务,并绑定到它的code:

I have tried to start a service and bind to the service in my Activity's onCreate() method. When I try to call a function from service like commSessionManagerService.startCommandUpperM() afterwards, a NullPointerException occurs. Here is the code that I use to start the service and bind to it:

    Intent startIntent = new Intent(this, CommSessionManagerService.class);
    startService(startIntent);
    Intent bindIntent = new Intent(this, CommSessionManagerService.class);
    bindService(bindIntent, conn, Context.BIND_AUTO_CREATE);

如果我移动功能 startCommandUpperM() onStartCommand() CommSessionManagerService 的onCreate 方法将需要几秒钟才能完成。作为一个相关的说明,我有一个创建和启动了 startCommandUpperM()功能的线程。

If I move the function startCommandUpperM() to onStartCommand() in the CommSessionManagerService, the onCreate method will take several seconds to complete. As a related note, I have a created and started a thread in the startCommandUpperM() function.

推荐答案

这是因为你的服务实际上是绑定在UiThread。由于的onCreate 也运行在UiThread,你在 Handler.post调用 bindService 的结果(可运行)算得上是主线程的处理程序。

This is because your Service is actually bound on the UiThread. As onCreate also runs on UiThread, your call to bindService result in Handler.post(Runnable) be called on the main thread's handler.

所以,当 bindService 返回时,服务是不是已经绑定。 为了解决这个问题,你应该利用内幕 ServiceConnection.onServiceConnected您的服务把你的code()

So when bindService returns, the Service isn't already bound. To circumvent this problem, you should put your code using your Service inside ServiceConnection.onServiceConnected().