Reputation: 141
My project has a light switch which has an IP address and port and accepts strings to control. I am trying to create an application to switch this on and off. My code works, however after the first click, there is a significant delay between the next click and the switch actually switching.
I have a button for on and off. main.java:
package com.android.lswitch;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class lightswitch extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Handle swon button
Button swon = (Button) findViewById(R.id.swon);
swon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sw(true);
}
});
// Handle swoff button
Button swoff = (Button) findViewById(R.id.swoff);
swoff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sw(false);
}
});
}
private void sw(boolean swstate) {
if (swstate == true) {
Thread swonThread = new Thread(new swon());
swonThread.start();
}
if (swstate == false) {
Thread swoffThread = new Thread(new swoff());
swoffThread.start();
}
}
}
and button on java: package com.android.lswitch;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class swon implements Runnable {
public static final String SERVERIP = "10.0.0.25";
public static final int SERVERPORT = 4000;
public void run(){
try {
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Socket socket = new Socket(serverAddr, SERVERPORT);
String swon = "A55A6B0550000000FFFBDE0030C8";
String but0 = "A55A6B0500000000FFFBDE002066";
PrintWriter out = new PrintWriter( new BufferedWriter
( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(swon);
out.println(but0);
socket.close();
} catch(Exception e) {
}
finally {
}
}
}
button off is virtually the same but with different strings. I'm new to android coding (and java coding) so can't see where the hold up is. Do I need to flush the strings somewhere? or is there a better way of tackling this project?
Cheers
Upvotes: 0
Views: 1018
Reputation: 6958
PrintWriter
may be buffered, so you should definitely flush()
it before issuing any close()
operation on the underlying socket.
It is also preferable to call PrintWriter.close()
instead of Socket.close()
, e.g., in a finally
block, such as:
PrintWriter out = new PrintWriter( new BufferedWriter
( new OutputStreamWriter(socket.getOutputStream())),true);
try {
out.println(swon);
out.println(but0);
out.flush();
} finally {
out.close();
}
Upvotes: 1