I have project where android app is connecting to tcp server and is receiving data from it. Server works in a loop:
1. Wait for connection.
2. Accept client.
3. Send data to client.
4. Close connection.
5. Back to 1.
My application is connecting to the server in onCreate() method and it works, it is receiving data, but i want it to work in a loop so it can perform connection again.
Here is an application code.
onCreate method:
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 method:
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);
}
String received from server looks like this:
"temperature;humidity;light"
I tried refreshing my Activity like people say in this topic: here and my application is not even starting and I'm getting this warning:
W/art: Suspending all threads took: 10.644ms.
And my question is:
Is there any way I can refresh my application and it will connect again to the server and refresh values on screen? It is working if i close app and reopen it again. I appreciate any help.