我的应用程序出现了一个奇怪的问题。该应用程序由一个服务和一个活动组成,服务必须“始终”运行,而活动只是一个控制服务的界面,并且不需要运行很多。
所以我想在我的Activity onCreate()
中创建服务,如果它尚未运行,然后绑定到它。代码如下所示:
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出现了,在我的服务的onCreate()
- 方法中有一个活动的断点,持续2秒,然后终止。
在断开调试器之前,Logcat不会显示任何错误。
我的服务onCreate()
的第一行是android.os.Debug.waitForDebugger();
在我添加该调用之前,调试器从未附加到服务。
有没有人知道这个问题或更好,一个解决方案?
答案 0 :(得分:0)
如果将mService.doSomeStuff()移动到onServiceConnected()会发生什么?您不需要执行while()循环来等待它
bindService返回什么?如果没有错误发生,它应该返回
在onServiceConnected()中添加一些日志以查看它何时被调用
您的服务在构造函数中做了什么?它挂在哪里吗?