简体   繁体   中英

Keeping a socket connection open while sending commands on Android

This week I started Android programming, and this is what I'd like to achieve through my first application. I'm new to both Java and Android, but I have some Python experience.

I have a python server running on my raspberryPi that, depending on the commands received, fades a bunch of RGB leds.

I'm now trying to build an Android app that sends commands to the server through sockets.

There is an input box and a button: when the button is pressed, i want the entered data to be sent to the server.

I wrote it and it works, but I believe there is something wrong with my implementation. I want the app to open a socket connection and, while keeping it open, send commands to the server.

When clicked, the button passes the entered command and server address to ASyncTask, which then opens the connection to the server and sends the command. However, to send a new command, the connection has to be closed and opened again, and ASyncTask called another time.

I don't need this: the connection should stay open all the time.

Here's my code (the important bits):

This gets the input and sends it to ASyncTask when the button is clicked:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final EditText inputText = (EditText) findViewById(R.id.editText2);
    final Button sendButton = (Button) findViewById(R.id.button);
    final TextView text = (TextView) findViewById(R.id.textView3);

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String outputText = inputText.getText().toString().concat("\n");
            text.append(outputText);
            ConnectTask task = new ConnectTask();
            task.execute("192.168.1.3:1322", inputText.getText().toString());

        }
    });

And this is my ASyncTask subclass:

private class ConnectTask extends AsyncTask<String, Void, Void>{
    @Override
    protected Void doInBackground(String... strings){
        String[] spl = strings[0].split(":");
        String address = spl[0];
        int port = Integer.parseInt(spl[1]);
        SocketAddress sockaddr = new InetSocketAddress(address, port);
        Socket socket = new Socket();
        try{
            socket.connect(sockaddr, 5000);
        } catch (IOException e){
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        try {
            bw.write(strings[1]);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Thanks in advance for your help!

What you really want is called a Service . Services are a bit complex, and probably a more involved answer than I really want to type here, but here's a few things:

  1. You want a bound service, so you can send messages from your app to the service and back.
  2. You might look at the Coursera course https://class.coursera.org/posa-002/ , which is currently covering something similar to what you will want.
  3. Read the documents I linked above. Services need some careful thought, but the documents are good.

Services are good because they operate in the background, can be on their own thread, and interact with activities and other services. You could open a connection on connect, talk in the background by sending messages back and forth between the activity and service, and disconnect the service when you are done. All is relatively straightforward, although it does involve some fairly complex connections.

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