Android start service issue in onCreate of Activity

久未见 提交于 2019-12-12 01:47:08

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/21881617/android-start-service-issue-in-oncreate-of-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!