Android在活动中的onCreate启动服务问题 [英] Android start service issue in onCreate of Activity

查看:128
本文介绍了Android在活动中的onCreate启动服务问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图启动一个服务,并绑定到我的活动的的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().

这篇关于Android在活动中的onCreate启动服务问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆