2017-02-18 86 views
0

我有项目,Android应用程序连接到tcp服务器,并从它接收数据。服务器工作在一个循环中:
1.等待连接。
2.接受客户端。
3.发送数据到客户端。
4.关闭连接。
5.回到1
刷新活动连接到服务器

我的应用程序连接到服务器onCreate()方法和它的作品,它正在接收数据,但我希望它在一个循环工作,所以它可以再次进行连接。

这里是一个应用程序代码。
onCreate方法:

protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     temperatureValue = (TextView) findViewById(R.id.temperatureValue); 
     humidityValue = (TextView) findViewById(R.id.humidityValue); 
     lightValue = (TextView) findViewById(R.id.lightValue); 


     new Thread(new ClientThread()).start(); 
    } 

ClientThread:

class ClientThread implements Runnable 
{ 
    String data; 

    @Override 
    public void run() 
    { 
     try 
     { 
      InetAddress serverAddr = InetAddress.getByName(SERVER_IP); 
      socket = new Socket(serverAddr, SERVER_PORT); 
     } 
     catch (UnknownHostException e1) 
     { 
      e1.printStackTrace(); 
     } 
     catch (IOException e2) 
     { 
      e2.printStackTrace(); 
     } 
     try 
     { 
      InputStream in = socket.getInputStream(); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      data = br.readLine(); 

      splitData(data); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 

    } 

splitData方法:

public void splitData(String data) 
    { 
     String[] parts = data.split(";"); 
     String temperatura, wilgotnosc, swiatlo; 

     temperatura = parts[0]; 
     wilgotnosc = parts[1]; 
     swiatlo = parts[2]; 

     temperatureValue.setText(temperatura.substring(0, 5)); 
     humidityValue.setText(wilgotnosc.substring(0, 5)); 
     lightValue.setText(swiatlo); 
    } 
从服务器接收

字符串看起来像这样:
“温度;湿度;光”

我尝试刷新我的活动,就像人们在这个主题中所说:here和我的应用程序甚至没有开始,我得到这个警告:
W /艺术:暂停所有线程花费:10.644ms。

我的问题是:
有什么办法,我可以刷新我的应用程序,它将再次连接到服务器,并在屏幕上刷新值?它正在工作,如果我关闭应用程序并重新打开它。我感谢任何帮助。

回答

0

splitData(data);

伪代码:

下面的代码在这里,你可以实现一个方法做refreshConnection

public void refreshConnection() { 
    Put your time limit when to refresh and go run the run() method again. 
}