gpt4 book ai didi

android - 如何延迟 onServiceConnected 调用

转载 作者:行者123 更新时间:2023-11-30 03:25:41 28 4
gpt4 key购买 nike

我正在实现 Service,它与服务器建立 TCP 连接,然后允许客户端通过此连接传递消息。客户端使用 bindService 调用连接到服务。结果 onServiceConnected 在客户端 ServiceConnection 对象中调用。问题是 onServiceConnected 在从 bindService 返回后立即调用,但此时我的 Service 尚未与服务器建立连接。我可以在未建立连接时以某种方式延迟 onServiceConnected 调用吗?如果不可能,请为我的案例提出一些好的模式。谢谢。

最佳答案

您应该按如下方式进行:

服务代码:

class MyService implements Service {
private boolean mIsConnectionEstablished = false;

// Binder given to clients
private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
public MyService getService() {
// Return this instance of LocalService so clients can call public
// methods
return MyService.this;
}
}

public interface OnConnectionEstablishedListener {
public void onConnectionEstablished();
}

private OnConnectionEstablishedListener mListener;

@Override
public void onCreate() {
super.onCreate();

new Thread( new Runnable() {
@Override
void run() {
//Connect to the server here

notifyConnectionEstablished();
}
}).start();
}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

private void notifyConnectionEstablished() {
mIsConnectionEstablished = true;

if(mListener != null) {
mListener.onConnectionEstablished();
}
}


public void setOnConnectionEstablishedListener(
OnConnectionEstablishedListener listener) {

mListener = listener

// Already connected to server. Notify immediately.
if(mIsConnectionEstablished) {
mListener.onConnectionEstablished();
}
}
}

Activity 代码:

class MyActivity extends Activity implements ServiceConnection,
OnConnectionEstablishedListener {

private MyService mService;
private boolean mBound;

@Override
public void onCreate() {
super.onCreate();

//bind the service here
Intent intent = new Intent(this, MyService.class);
bindService(intent, this, BIND_AUTO_CREATE);
}

@Override
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;

mService.setOnConnectionEstablishedListener(this);
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}

@Override
public void onConnectionEstablished() {
// At this point the service has been bound and connected to the server
// Do stuff here
// Note: This method is called from a non-UI thread.
}
}

关于android - 如何延迟 onServiceConnected 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18287918/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com