作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在编写服务时遇到问题,该服务应该适用于多个 Activity 。我编写了一个简单的服务和一个进行绑定(bind)并可以返回服务对象的中介类。这是简单的服务类:
public class ServerConnectionService extends Service{
private static final String TAG = "ServerConnectionService";
private final Binder binder=new LocalBinder();
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy(){
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class LocalBinder extends Binder {
ServerConnectionService getService() {
return ServerConnectionService.this;
}
}
}
这是中介类:
public class ServiceConnectionBinder{
private ServerConnectionService m_SrvConnection=null;
private ServiceConnection m_OnService;
private boolean m_IsBound;
private Activity m_Client;
public ServiceConnectionBinder(Activity i_Activity)
{
m_IsBound = false;
this.m_Client = i_Activity;
this.m_OnService=new ServiceConnection() {
public void onServiceConnected(ComponentName className,IBinder rawBinder) {
m_SrvConnection=((ServerConnectionService.LocalBinder)rawBinder).getService();
}
public void onServiceDisconnected(ComponentName className) {
m_SrvConnection=null;
}
};
doBindService();
Log.d("ServiceConnectionBinder", "finished Ctor");
}
private void doBindService() {
if(!m_IsBound)
{
m_Client.bindService(new Intent(m_Client, ServerConnectionService.class), m_OnService, Context.BIND_AUTO_CREATE);
m_IsBound = true;
}
if(m_SrvConnection == null)
{
Log.d("ServiceConnectionBinder",".doBindService cannot bind " + ServerConnectionService.class.toString() + " to " + this.toString());
}
}
public void doUnbindService() {
if (m_IsBound) {
// Detach our existing connection.
m_Client.unbindService(m_OnService);
m_IsBound = false;
}
}
public ServerConnectionService getServerConnectionService()
{
if(m_IsBound)
{
Log.d("ServiceConnectionBinder", "getServerConnectionService m_IsBound = " + m_IsBound);
}
return m_SrvConnection;
}
}
客户端 Activity 有以下数据成员:
private ServiceConnectionBinder m_SrvcConnectionBinder=null;
private ServerConnectionService m_SrvConnection=null;
并在 onCreate() 中执行以下代码:
m_SrvcConnectionBinder = new ServiceConnectionBinder(this);
m_SrvConnection = m_SrvcConnectionBinder.getServerConnectionService();
问题是在 onCreate() 之后,m_SrvConnection 始终为 null。
如果您有任何其他实现方法,我们非常欢迎您分享..
最佳答案
problem is that after the onCreate(), the m_SrvConnection is always null.
当然。绑定(bind)请求甚至不会开始,直到主应用程序线程再次获得控制权(即,您将控制权返回给操作系统)。
在调用 onServiceConnected()
之前,您不能使用 m_SrvConnection
。
关于android - 如何在多个 Activity 中使用服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6281330/
我是一名优秀的程序员,十分优秀!