我与arduino的蓝牙连接有问题,这是我第一次尝试通过蓝牙将apk与设备连接。 问题是,第一次使用按钮后,必须向设备发送消息“ on” /“ off”(无论是哪个,但对于第一个消息都很重要),设备才能正常工作。 但是之后,我无法再次发送消息,只是敬酒我“请重启您的蓝牙”-btSocket不再连接。 有什么想法或建议吗? 感谢帮助。
public class BluetoothList extends AppCompatActivity {
private BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
private ListView listView;
private String[] sName, sAddress;
private BluetoothAdapter myBluetooth;
private BluetoothSocket btSocket = null;
private BluetoothDevice dispositivo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_list);
listView = findViewById(R.id.lvBluetooth);
turningOn();
if(bAdapter==null){
Toast.makeText(getApplicationContext(),"Bluetooth Not Supported",Toast.LENGTH_SHORT).show();
}
else{
Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
ArrayList address = new ArrayList();
ArrayList name = new ArrayList();
if(pairedDevices.size()>0){
for(BluetoothDevice device: pairedDevices)
{
String devicename = device.getName();
String macAddress = device.getAddress();
address.add(macAddress);
name.add(devicename);
}
sName = (String[]) name.toArray(new String[0]);
sAddress = (String[]) address.toArray(new String[0]);
BluetoothLVAdapter bAdapter = new BluetoothLVAdapter(this, sName, sAddress);
listView.setAdapter(bAdapter);
}
}
}
private void turningOn()
{
Button trnOn = findViewById(R.id.btn_turnON);
Button trnOFF = findViewById(R.id.btn_turnOFF);
trnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
BluetoothConnection();
if (btSocket.isConnected()){
try {
btSocket.getOutputStream().write("on".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}else{
Toast.makeText(getApplicationContext(), "Reboot your bluetooth please", Toast.LENGTH_SHORT).show();
}
}
});
trnOFF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
BluetoothConnection();
if (btSocket.isConnected()){
try {
btSocket.getOutputStream().write("off".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}else{
Toast.makeText(getApplicationContext(), "Reboot your bluetooth please", Toast.LENGTH_SHORT).show();
}
}
});
}
private void BluetoothConnection()
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
dispositivo = myBluetooth.getRemoteDevice(sAddress[0]);//connects to the device's address and checks if it's available
try {
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
} catch (IOException e) {
e.printStackTrace();
}
try {
btSocket.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
}