0

我的应用程序有一个奇怪的问题。App由一个Service和一个Activity组成,服务必须“一直”运行,而Activity只是一个控制服务的接口,不需要运行很多。onCreate()因此,如果它尚未运行,我想在我的 Activity 中创建该服务,然后绑定到它。代码如下所示:

private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder binder) {
            mService= ((MyService.LocalBinder) binder).getService();
            mService.setView(ChatdroidActivity.this);
        }

        public void onServiceDisconnected(ComponentName className) {
            Controler = null;
        }
    }; 

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initUI();

        if(!MyService.isRunning()){
            Intent s= new Intent(this, MyService.class);
            startService(s);


        }

        bindService(new Intent(this, MyService.class), mConnection,
                Context.BIND_AUTO_CREATE);  

        while(mService == null){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        mService.doSomeStuff();
}

问题是服务似乎没有启动。该应用程序处于while循环中,直到我在Android消息之后断开调试器,我的应用程序冻结了。当我在网上搜索解决方案时,突然我的 Eclipse 出现了,在我的 Service 方法中有一个活动断点onCreate(),持续了大约 2 秒钟,然后它终止了。在我断开调试器之前,Logcat 不会显示任何错误。我的服务的第一行onCreate()android.os.Debug.waitForDebugger(); 在我添加该调用之前,调试器从未附加到服务。

有谁知道这个问题或更好的解决方案?

4

1 回答 1

0
  • 如果将 mService.doSomeStuff() 移动到 onServiceConnected() 会发生什么?你不需要做一个 while() 循环来等待它

  • bindService 返回什么?如果没有发生任何错误,它应该返回 true

  • 在 onServiceConnected() 中输入一些日志以查看它何时被调用

  • 您的服务在承包商中做什么?它挂在那里的某个地方吗?

于 2012-04-20T09:11:50.243 回答