【问题标题】:Android start service issue in onCreate of ActivityActivity 的 onCreate 中的 Android 启动服务问题
【发布时间】:2014-02-19 13:15:27
【问题描述】:

我尝试在我的 Activity 的onCreate() 方法中启动一个服务并绑定到该服务。之后,当我尝试从commSessionManagerService.startCommandUpperM() 之类的服务调用函数时,会出现NullPointerException。这是我用来启动服务并绑定到它的代码:

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

如果我在CommSessionManagerService 中将函数startCommandUpperM() 移动到onStartCommand(),则onCreate 方法将需要几秒钟才能完成。作为相关说明,我在 startCommandUpperM() 函数中创建并启动了一个线程。

【问题讨论】:

  • 请发布更多代码。你什么时候打电话给startCommandUpperM();?你的活页夹有用吗?
  • 在startCommandUpperM中,代码如下: csThread = new CommSessionThread(this); csThread.start();并在 CommSessionThread ( public void run() { while(runningFlag) { switch(commSession.getSessionState()) { case PsmConstants.STATE_TRANSMIT: commSession.transmit(); break; case PsmConstants.STATE_RECEIVE: commSession.receive(); break; case PsmConstants.STATE_SUSPEND: break; case PsmConstants.STATE_IDLE: break; default: break;} } })
  • 您是否在服务中的 onBind() 中返回自己的 CommSessionManagerService 对象?请发布 onBind() 代码。

标签: android service android-activity oncreate


【解决方案1】:

这是因为你的Service 实际上是绑定在 UiThread 上的。由于 onCreate 也在 UiThread 上运行,因此您对 bindService 的调用导致在主线程的处理程序上调用 Handler.post(Runnable)

所以当bindService 返回时,Service 尚未绑定。 为了避免这个问题,你应该把你的代码使用你的服务放在ServiceConnection.onServiceConnected()中。

【讨论】:

  • 谢谢 :),它运行良好,但是现在当我将 startCommandUpperM 放入 onServiceConnected 时,onCreate 方法将需要几秒钟,我创建了一个线程并在 startCommandUpperM 中启动,可以吗?
  • 我觉得还可以=)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多