0
我很担心Android手机和Arduino蓝牙模块(HC-06)之间的蓝牙通信。我在代码的连续性方面遇到了问题。如果我开始调试,那么在程序到达mConnectThread.start()之前根本没有问题。线。此时它会“停止”:停留在调试模式下,但我徒劳地按下Step,不会继续。显然它不会跳转到ConnectThread类,我不知道为什么发生这种情况。为什么不mConnectThread.start()使程序继续到ConnectThread类?
非常感谢您的帮助!
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice;
private ConnectThread mConnectThread;
private String MAC = "30:14:10:17:06:93";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView supportsBTorNot = (TextView) findViewById(R.id.supportsBTorNot);
TextView listPairedDevices = (TextView) findViewById(R.id.listPairedDevices);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
supportsBTorNot.setText("The device does not support bluetooth.");
}
else{
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
else{
supportsBTorNot.setText("The device supports bluetooth.");
}
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
listPairedDevices.setText(pairedDevices.toString());
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if(device.getAddress().equals(MAC)) {
mDevice = device;
break;
}
}
}
if (mDevice == null) {
//Device is not paired yet
//Need to initiate a connection request
}
mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private ConnectedThread mConnectedThread;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
TextView socketConnected = (TextView) findViewById(R.id.socketConnected);
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
if (mmSocket.isConnected()) {
socketConnected.setText("The socket is established successfully.");
}
else {
socketConnected.setText("The socket could not be stablished.");
}
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
}
谢谢你的帮助! :) – lazarea
没问题,很高兴我能帮上忙。 –