Question

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?

Was it helpful?

Solution

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().

OTHER TIPS

I wouldn't know why it's not possible.

Wether it's a good idea or not, I don't know.

My two cents to achieve it your way is, create a singleton class.

singleton pattern example

Credits for the article go to http://www.javacoffeebreak.com/

Aside from their barebone implementation, make sure you have a method to retrieve your socket and just as important, close your socket. Which you can do when your app gets destroyed. I believe the application object's onDestroy method is a decent place to do this as from what I remember that will be the last onDestroy method called before your application is taken completely out of memory.

Having that said.. what if your application crashes? you will need to clean up somehow. Creating a socket on demand will probably be the safest way.

Note that, if you have a socket that is always open throughout activities it is easy to forget that you need to close it. Another reason to manage the socket per activity instead of globally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top