0

我试图在我的 android 应用程序的单独线程中定义一个侦听器,但是,线程在此之前退出并且不等待调用回调函数。

下面是代码片段:

new Thread(new Runnable() {
  public void run() {
    ServiceConnection conn = new ServiceConnection() {
      public void OnServiceConnected(ComponentName name, IBinder service) {
        obj = <AIDL interface>.Stub.asInterface(service);
      }
      public void onServiceDisconnected(ComponentName name) {
        obj = null;
      }
      Intent intent = new Intent("<service name>");
      context.startService(intent);
      boolean status = context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}).start();

现在,当我从主线程启动这个线程并等待 onServiceConnected() 发生时,它会永远等待并且永远不会被调用。我还检查了该线程的状态,它显示“已终止”。知道如何解决这个问题吗?

4

1 回答 1

0

您需要重新考虑应用程序的设计。一些你应该知道答案的问题:

您是否需要与服务进行双向交互,或者您可以简单地向服务发送“请求”?

服务中执行的操作是否足够快,可以在 UI 线程中完成,还是需要在单独的线程中运行?

很有可能您可以使服务成为 IntentService 并通过使用 StartService(Intent) 发送请求与它进行交互,而根本不需要绑定到服务,但是如果没有上述问题的答案,就很难说清楚。

编辑:

在绑定到服务之前,在 run 方法中将 m_stopping(一个新的成员变量)设置为 false。

发出绑定请求后:

while(!m_stopping)
{
   do_some useful work here (otherwise, why have a thread?)
   This may include calling unbindService() when you are done.
}

并且在 ServiceConnection::onServiceDisconnected(component) 方法的实现中将 m_stopping 设置为 false。

于 2013-11-05T16:15:33.543 回答