TCP / IP客户端在各种Android活动之间接收和发送

时间:2016-12-09 10:44:47

标签: android android-activity tcp client

我需要帮助来了解如何使用服务器连接Android上的tcp客户端,连接本身不是问题,而是活动之间的交换。

我将尝试用附图解释。

我需要使用TCP / IP套接字启动与服务器的连接。在搜索网络后,我发现了几个例子,但都使用了一个活动,但我需要它按如下方式工作:

enter image description here

1 - 让我们在主要活动中说我点击CONNECT开始连接。

2 - 但是我需要单击ACTIVITY_A按钮打开另一个活动,同时保持主活动中已经打开的连接,并继续在其ACTIVITY_A中发送和接收信息。

3 - 返回ACTIVITY_A,单击ACTIVITY_B执行上述相同的过程。

我迷失了使用哪种解决方案以及如何使用,asynctask,thread,singleton,intent,context。

2 个答案:

答案 0 :(得分:0)

您可以使用Android服务进行网络连接。另请查看Android Networking官方文档。此外,还有很多用于执行网络请求的库(如Robospice

答案 1 :(得分:0)

我编辑了上一条消息以告知我是如何解决的,它可能并不理想,但它正在发挥作用。

Act_Main

public class Act_Main extends AppCompatActivity implements Singleton.OnReceiveListener{

private Singleton sing;
String ip = "192.168.4.1";
int porta = 23;

Button btConectar, btActivityA, btActivityB;
TextView txtStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_main);

    btConectar = (Button) findViewById(R.id.btConectarID);
    btActivityA = (Button) findViewById(R.id.btActivityAID);
    btActivityB = (Button) findViewById(R.id.btActivityBID);
    txtStatus = (TextView) findViewById(R.id.txtStatusID);

}

public void conectar (View view){
    sing = Singleton.getInstance(ip, porta, this);
}

public void openActivityA(View view) {
    Intent it = new Intent(Act_Main.this, Activity_A.class);
    startActivity(it);
}

public void openActivityB(View view) {
    Intent it = new Intent(Act_Main.this, Activity_B.class);
    startActivity(it);
}

@Override
public void onReceive(String dataRx) {
    // Trata a informação recebida aqui.
    txtStatus.setText(dataRx);
}
}    

的Singleton

public class Singleton {
private static Singleton instancia = null;
private static OnReceiveListener orl = null;
private boolean running;
private static Client client;

private Singleton() {
}

public boolean isRunning() {
    return running;
}

public void setRunning(boolean running) {
    this.running = running;
}

public static interface OnReceiveListener {
    public void onReceive(String dataRx);
}

public static Singleton getInstance(String _ip, int _port, OnReceiveListener listener) {
    if (instancia == null) {
        client = new Client(_ip, _port);
        client.execute();
        instancia = new Singleton();
    }
    orl = listener;
    return instancia;
}

public void sendMsg(String str) {
    client.sendMessage(str);
}


private static class Client extends AsyncTask<Void, String, Void> {

    String dstAddress;
    int dstPort;
    String response = "";
    BufferedReader in;
    PrintWriter out;
    String incomingMessage;
    private boolean running;

    Client(String addr, int port) {
        dstAddress = addr;
        dstPort = port;
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        Socket socket = null;
        try {
            socket = new Socket(dstAddress, dstPort);
            running = true;
            // Cria um objeto PrintWriter para enviar mensagens ao servidor.
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            // Cria um objeto BufferedReader para receber mensagens do servidor.
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            Log.d(TAG, "In/Out created");

            while (running) {
                incomingMessage = in.readLine();
                if (incomingMessage != null) {
                    publishProgress(incomingMessage);
                }else{
                    running = false;
                }
                incomingMessage = null;
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... params) {
        orl.onReceive(params[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }

    private void sendMessage(String message) {
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
            Log.d(TAG, "Sent Message: " + message);
        }
    }

}
}

Activity_A

public class Activity_A extends AppCompatActivity implements Singleton.OnReceiveListener {

private Singleton sing;
String ip = "192.168.4.1";
int porta = 23;

Button btVoltar, btEnviar;
TextView txtRx, txtTx;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_a);

    btEnviar = (Button) findViewById(R.id.btEnviarID);
    btVoltar = (Button) findViewById(R.id.btVoltarID);
    txtRx = (TextView) findViewById(R.id.txtRxID);
    txtTx = (TextView) findViewById(R.id.txtTxID);

    sing = Singleton.getInstance(ip, porta, this);

}

@Override
public void onReceive(String dataRx) {
    txtRx.setText(dataRx);
}

public void Enviar (View view){
    sing.sendMsg(txtTx.getText().toString());
}

public void Voltar(View view) {
    this.finish();
}
}

Activity_B

public class Activity_B extends AppCompatActivity implements Singleton.OnReceiveListener {

private Singleton sing;
String ip = "192.168.4.1";
int porta = 23;

Button btVoltar, btEnviar;
TextView txtRx, txtTx;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    btEnviar = (Button) findViewById(R.id.btEnviarID);
    btVoltar = (Button) findViewById(R.id.btVoltarID);
    txtRx = (TextView) findViewById(R.id.txtRxID);
    txtTx = (TextView) findViewById(R.id.txtTxID);

    sing = Singleton.getInstance(ip, porta, this);

}

@Override
public void onReceive(String dataRx) {
    txtRx.setText(dataRx);
}

public void Enviar (View view){
    sing.sendMsg(txtTx.getText().toString());
}

public void Voltar(View view) {
    this.finish();
}
}

显然它没有完成,但它是一个开始。

感谢那些回复的人。