Bisakah seseorang menjelaskan kepada saya apa yang salah dengan kode berikut? Saya mencoba semuanya: menambahkan batas \n\r
untuk menunggu akhir baris dan beberapa cara lainnya. Saya selalu menerima data sampah. Jadi saya kembali ke kode awal saya.
Beberapa orang mengatakan kepada saya bahwa mungkin InputStream
yang tidak menerima data, tapi ini tidak memberi saya solusi.
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
// Creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
try {
// Create I/O streams for connection
tmpIn = socket.getInputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
}
public void run() {
byte[] buffer = new byte[1024]; // I tried all 128, 8, 256
int bytes;
while (true) {
try {
if (mmInStream.available()>0){
bytes = mmInStream.read(buffer);//read bytes from input buffer
bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
}
}
catch (IOException e) {
break;
}
}
}
}
private void setw() throws IOException {
blue_tv = findViewById(R.id.blue_tv);
blue_tv2 = findViewById(R.id.blue_tv2);
bluetoothConnectDevice();
mConnectedThread = new ConnectedThread(bluetoothSocket);
mConnectedThread.start();
}
private void bluetoothConnectDevice() throws IOException {
try {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
blue_address = bluetoothAdapter.getAddress();
pairedDevice = bluetoothAdapter.getBondedDevices();
if (pairedDevice.size() > 0) {
for (BluetoothDevice bt : pairedDevice) {
blue_address = bt.getAddress();
blue_name = bt.getName();
Toast.makeText(getApplicationContext(), "Cane connected", Toast.LENGTH_SHORT).show();
blue_status = "La canne est connectée !";
}
}
} catch (Exception e) {
e.printStackTrace();
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //get mobile bluetooth device
BluetoothDevice bd = bluetoothAdapter.getRemoteDevice(blue_address);//connect to the device
bluetoothSocket = bd.createInsecureRfcommSocketToServiceRecord(myUUID); //create a RFCOM (SPP) connexion
bluetoothSocket.connect();
try {
blue_tv.setText("Bluetooth Name : " + blue_name + "\nBluetooth Adress : " + blue_address);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_traject);
mySR = SpeechRecognizer.createSpeechRecognizer(this);
autoCompleteTextView = findViewById(R.id.actv);
try {
setw();
}catch (Exception e){
e.printStackTrace();
}
blue_status = "La canne n'est pas connectée.";
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
byte[] readBuff = (byte[]) msg.obj;
String readMessage = new String(readBuff,0,msg.arg1);
blue_tv2.setText("Data Received = " + readMessage+"\n"+"Data Length = "+readMessage.length());
}
}
};