I work on an Android app to remote control Led on/off, and change its brightness via HC-05 bluetooth connection on Anduino UNO, and have tried this topic: Android sample bluetooth code to send a simple string via bluetooth
- have set up Socket connection in this following code:
bluetoothDevice = bluetoothAdapter.getRemoteDevice(strAddress);
connectThread = new ConnectThread(bluetoothDevice);
connectThread.start();
- Press the Button in the app screen to send '1' or '0' to control Led on or off, by this followingcode: it works well.
public void onLed() {
if(mySocket != null){
try{
mySocket.getOutputStream().write("1".getBytes());
} catch (IOException e){
e.printStackTrace();
return;
}
}
}
- But when I send the
"progress"
value of a Seekbar through the following code, it could only work once, or just stop functioning if I moving the slide quicker, then all the buttons in the app stop functioning, no response when pressed down. Made some tests, seemed the socket still exist, not "null"
, and the mySocket.getOutputStream().write()
function blocked, does not work. And couldn't set up a new Socket immediately, unless back to the previous activity by finish()
, it works, could set up a new Socket connetion, and the "progress
" value could be sent out again.
barBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String str = Integer.toString(progress);
if (mySocket != null) {
try {
mySocket.getOutputStream().write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
mySocket = null;
connectSocket();
}
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
finish();
//mySocket = null;
}
});
- I only used ConnectThread to create Socket, since not receiving data into app, so the ConnectedThread is not applied.
So what the problem is? Any suggestion is appreciated. Should overwrite the onPause()
function?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…