Вопрос

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);

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.

Это было полезно?

Решение

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.

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().

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top