您好我在ANdroid中有一个带有tcp套接字连接的客户端服务器架构。我的服务'onStart()'中有一个套接字侦听器线程。我想以某种方式失去连接后重新连接到服务器。我该如何设计这个问题?我尝试了一些方法但是我在服务开始时遇到了无限循环...感谢您的回答。
监听器代码是这样的......
@Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "onSTARTED!!");
if(!mySocket.isConnected()){
connectiontoServer();
}
clientListenerThread = new Thread(new Runnable() { // TCP Socket Listener
public void run() {
String line = new String();
try {
while(mySocket.isConnected() && ((line = in.readLine()) != null)){
try{
Log.d(TAG, "service onStart-while true");
String[] tokens = line.split(MessageClass.ayirac);
Log.d(TAG+"-MSG", line);
tokens = line.split(MessageClass.ayirac);
int msgCase = Integer.parseInt(tokens[0]);
switch(msgCase){
case -5:
responseEntrance(line);
break;
case 1:
responseLogin1(line);
break;
case 2:
responseRegister2(tokens);
break;
default:
break;
}
}catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "CATCH1 !");
continue;
}
}
}catch(IOException e){
e.printStackTrace();
if(!mySocket.isConnected()){
Log.d(TAG,"ConnectionDOWN! in catch2");
stopAndDestroyMyActivity();
}
}
Log.d(TAG, "LISTENING FINISH!");
stopAndDestroyMyActivity();
}
});
clientListenerThread.start();
}
答案 0 :(得分:0)
如果你想在一段时间后连接使用Timer类: http://developer.android.com/reference/java/util/Timer.html