Search code examples
javaandroidsocketstcparduino

Android TCP error when I flush from android:onClick


I'm trying to connect ESP8266 module to an Android App. The Server runs into the module and the client runs in the Apk. The server runs great (I've tested with playstore apps). The problem is in the client. I found this Git: https://github.com/omplanet/async-socket-android to manage the connection. It connects great to the device, but when I put a button and try to use write function, I get the error: "Could not execute method for android:onClick". It happends when it uses BufferedWriter.flush()

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

    if(!hasPermissions(this, PERMISSIONS)){
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }
    tcpConection = new AsyncConnection(SERVER_IP,SERVERPORT,0,MainActivity.this);
    tcpConection.execute();

}
public void sendButton(View view){
    tcpConection.write("Hello torno!");
}

@Override
public void didReceiveData(String data) {

}

@Override
public void didDisconnect(Exception error) {

}

@Override
public void didConnect() {

}

Is there a way of not using flush so I can use Write inside a button method? Is there a better way to do it?


Solution

  • Because sendButton() executed in UI thread, and no internet work is allow in UI thread. Try to wrap "tcpConection.write("Hello torno!");" call in another threads runnable object like:

            new Thread(new Runnable() {
                @Override
                public void run() {
                    tcpConection.write("Hello torno!");
                }
            }).start();