2011-03-13 126 views
15

我不擅长英语,但我会尽力以良好的方式解释我的问题。
Android,unbind服务和onServiceDisconnected问题

所以,问题是:
1)我有一个本地服务
2)我启动它,然后绑定到它。 3)当我即将关闭该服务时出现问题。 onServiceDisconnected方法从我的实施类ServiceConnection永远不会被调用。如果我手动关闭它(从设置),或通过unbindService,或通过stopService,或通过组合unbindService和stopService - onServiceDisconnected仍然不会被调用。 我在做什么错?

短代码如下:

protected ServiceConnection mServerConn = new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName name, IBinder binder) { 
     Log.d(LOG_TAG, "onServiceConnected"); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName name) { 
     Log.d(LOG_TAG, "onServiceDisconnected"); 
    } 
} 

public void start() { 
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(i, mServerConn, Context.BIND_AUTO_CREATE); 
    mContext.startService(i); 
} 

public void stop() { 
    mContext.stopService(new Intent(mContext, ServiceRemote.class)); 
    mContext.unbindService(mServerConn); 
} 

我下的Android 2.2

回答

23

onServiceDisconnected的模拟器测试此代码只在极端情况下调用(坠毁/杀死)。

这对于本地服务来说不太可能发生,因为所有的应用程序组件通常运行在相同的进程中......意思是说,除非您意图解除绑定或销毁服务,否则它应该保持连接状态,它。

+1

好的,谢谢。我没有想到,这是一个错误或别的什么。所以我将来自onServiceDisconnected()的针数据(代码)复制到stop()。现在按我的意愿工作。 – UAS 2011-03-14 11:33:35

+0

这是正确的。但是在调用unbindService(连接)之后,我能够调用myservice(service)类中存在的公共方法。所以,unbindservice()方法没有意义吗?但是通过调用onDestroy()来销毁该服务。 – yokks 2011-03-27 17:25:37

1

我在bindService中使用了Context.BIND_AUTO_CREATE。在完成适合我的工作之后,我会提出相同的问题。

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