简体   繁体   中英

Using a socket instantiated from main activity in another activity

I created socket in main activity

public class MainActivity...{
..

public void sendToServer(String msg){
out.println("start");
}
..
socket = new Socket(serverAddr, SERVER_PORT); //Socket Creation
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                            .getOutputStream())), true); //stream to kick  data to server
}

If I call sendToServer("hi") on Button click from main Activity, I can see msg in server side. I was trying to call it from another activity somehow like

MainActivity con = new MainActivity();
con.sendToServer("hii");

Confused! how do I make it happen? -_-

I would write some thing like this . To create singleton class.

public class SocketClient {

    private static SocketClient sClient;

    private SocketClient() {

    }

    public synchronized static SocketClient getInstance() {
        if (sClient == null) {
            sClient = new SocketClient();
        }
        return sClient;
    }

    public void connect() {
        //Your connection code will come here
    }

    public void disconnect() {
        //Your disconnection code will come here
    }

    public void sendMessage(String message) {
        // message sending will code 
    }

}

You can access it anywhere in the application.

@Krish's approach is a good one, but I think some more explanation is needed:

From an object oriented view: You should move that Socket implementation to a separate type, because the Activity must not know about it; make your own interface and name it based on it's purpose (eg 'SaySomethingService'). That way you can test your Activity better (you don't need to create Sockets during a Unit test, which is nice), and you can change your implementation, without having to change your Activity (wich is nice, too).

(Other than that: I dislike the Singleton Pattern, some even argue, it's an antipattern. And there are more elegant solutions - but that depends on the requirements, the size, etc; in the end, it depends on the dev's who write and maintain the app.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM