从其他活动访问类或单例

时间:2015-01-06 17:07:27

标签: java android sockets singleton

所以我有网络套接字类应该处理我想要在我的应用程序运行时运行的套接字连接。问题是我不知道如何引用课程而不仅仅是开始一个新课程。

要开始一个新的,我会这样做:

Networker network = null;
try {
    network = new Networker(SERVER_IP, SERVERPORT);
    new Thread(network).start();

然后我可以这样做:(来自我刚才做过的同样的活动)

 network.send("helloworld");

如何在不进行全新套接字连接的情况下在任何类中执行network.send?

编辑: 这是我的Networker类:​​

public class Networker implements Runnable, Closeable {
    private final Socket clientSocket;
    private final PrintWriter out;
    private final BufferedReader in;
    private volatile boolean closed = false;

    public Networker(String hostname, int port) throws IOException {
        clientSocket = new Socket(hostname, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }

    public void run() {
        try {
            for(String fromServer; (fromServer = in.readLine()) != null;)
                System.out.println("Server: " + fromServer);
        } catch (IOException ex) {
            if (!closed)
                Log.i("logging", "error")   ;
        }
    }

    public void send(String line) {
        out.println(line);
    }

    public void close() {
        closed = true;
        try { clientSocket.close(); } catch (IOException ignored) { }
    }
}

0 个答案:

没有答案