我很难为最新版本的Android找到这个问题的答案。
我想完全务实地连接到蓝牙设备或蓝牙串行模块。我知道设备的名称和引脚,并且我打算在我最初超出范围的情况下尝试连续连接到设备,或者出于某种原因断开连接。
我有以下代码,需要使用必要的蓝牙代码填充它。
// Connect the bluetooth adaptor
BA = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(getApplicationContext(),"Checking bluetooth...",Toast.LENGTH_LONG).show();
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(),"Adaptor enabled",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"Adaptor already enabled", Toast.LENGTH_LONG).show();
}
// Start a background thread that attempts to connect to the board
Runnable bluetoothBackgroundRunnable = new Runnable() {
String bluetoothID = "ID GOES HERE"; // TODO: Change this to device name!
String securePin = "1234"; // TODO: Change this to device pin!
@Override
public void run() {
// Attempt to connect...
Toast.makeText(getApplicationContext(),"Attempting to connect...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
bluetoothConnectHandler.postDelayed(this, 1000);
}
};
bluetoothConnectHandler.postDelayed(bluetoothBackgroundRunnable, 100);