The basic idea is that when the app starts a class will simply establish a socket connection to server and define output and input streams, those which should be accessed through all different activities that requires interaction so the socket must be always alive and ready.
My thoughts so far is to create a class that will simply create socket and connections:
public class connection {
private String HostIPaddress = "XXX.XXX.XXX.XXX";
private int PORT = XXXX;
public Socket sock = null;
public DataOutputStream out = null;
public DataInputStream in = null;
public void assignStreams(){
try{
sock = new Socket(getHostIPaddress(),getPORT());
out = new DataOutputStream(sock.getOutputStream());
in = new DataInputStream(sock.getInputStream());
}catch (Exception ex) {
Log.i("Connection Error",ex.toString());
}
}
}
and then from the activity that run first, create a static object of this class and all other activities can access this object.. It sounds that this would work but I was wishing for some more thoughts or feedback?
No, not a good idea. The user can switch off internet at any point in time and your class is using a network connection when one may not be needed at all. Cleaning up after the socket is also impossible. How do you know when to close()
it ?
You are just better off creating these as needed. Your class also has poor encapsulation.
public Socket sock = null;
public DataOutputStream out = null;
public DataInputStream in = null;
These streams can be reassigned at any time. Protect them with getters() and setters().