你好,我想通过蓝牙将arduino的二进制文件发送到我的android应用。我已经写了一个可以成功建立通信并能够接收数据的应用程序。但是,在通信过程中缺少很多字节。奇怪的是,当我使用蓝牙终端应用程序时会收到每个字节。这表示通信正常,但我的应用程序未触发接收事件或类似事件。
我的代码:
private final Semaphore sem = new Semaphore(1, true);
@Override
protected void onCreate(Bundle savedInstanceState) {
img = new ImageSaver("image2.jpg", this);
bluetoothModule = new BluetoothSPP(this);
if (!bluetoothModule.isBluetoothAvailable()) {
output.append("Bluetooth is not available on this device");
} else {
bluetoothModule.enable();
bluetoothModule.setupService();
bluetoothModule.startService(BluetoothState.DEVICE_OTHER);
bluetoothModule.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
public void onDeviceConnected(String name, String address) {
if(name.equals("bilderstutzen"))
output.append("Connected to bilderstutzen");
}
public void onDeviceDisconnected() {
output.append("Connection lost");
}
public void onDeviceConnectionFailed() {
output.append("Unable to connect");
}
});
bluetoothModule.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() {
@Override
public void onDataReceived(byte[] data, String message) {
try{
sem.acquire();
//Log.d("save image", String.valueOf(img.length));
} catch (InterruptedException e) {
e.printStackTrace();
}
img.saveImage(data);
sem.release();
}
});
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == BluetoothState.REQUEST_CONNECT_DEVICE)
if(resultCode == Activity.RESULT_OK) {
if(data != null)
bluetoothModule.connect(data);
Log.d("connecting", "works");
}
else if(requestCode == BluetoothState.REQUEST_ENABLE_BT) {
if(resultCode == Activity.RESULT_OK) {
bluetoothModule.setupService();
//bluetoothModule.startService(BluetoothState.DEVICE_OTHER);
//setup();
} else {
output.append("bluetooth not enabled");
finish();
// Do something if user doesn't choose any device (Pressed back)
}
}
}
saveImage方法的简化版本:
public void saveImage(byte[] img){
for(byte b : img){ //just prints out the received data. With around 2000KB of data Im Missing around 200bytes
Log.d("save image", String.format("%02x", b));
}
}
希望您能帮助我解决这个问题!