我在service中建立tcp连接到服务器,但是程序关掉之后tcp连接会先断开一下然后自己连接上,但是程序已经干掉了。再次打开程序的话,就会有两个tcp连接连接上,如图
public class MyService extends Service {
/*------------------------------------------------------------------------------------*/
Socket socket = null;
boolean IfConnect = true;
boolean IfReader = false;
OutputStream outputStream = null;
InputStream inputStream = null;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onDestroy(){
Log.i("service:","service destroy!");
super.onDestroy();
}
@Override
public void onCreate(){
Log.i("service:","service create!");
super.onCreate();
link();
}
class Connect_Thread extends Thread{
public void run(){
InetAddress ipaddress;//定义一个变量用于存储ip
try{
//判断socket状态防止重复执行
if(socket == null){
//ipaddress = InetAddress.getByName("192.168.1.10");
ipaddress = InetAddress.getByName("192.168.2.17");
int port = Integer.valueOf("30000");
socket = new Socket(ipaddress,port);
//获取socket输入流和输出流
inputStream = socket.getInputStream();
outputStream= socket.getOutputStream();
//新建一个线程读数据
MyService.ThreadReadData t2 = new MyService.ThreadReadData();
t2.start();
}
}catch (Exception e){
e.printStackTrace();
}
}
}