BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
(2)接下来,你需要确保蓝牙处于开启的状态。调用isEnabled()方法来检查蓝牙目前是否可用。如果该方法返回false,那么蓝牙处于不可用的状态。为了请求蓝牙设备的开启,使用ACtiON_REQUEST_ENABLE的Intent,并调用startActivityForResult()方法。这将会通过系统设置开启你的蓝牙,例如:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
调用该方法后,一个请求开启蓝牙的对话框将会出现在屏幕上。如果用户点击确认,那么系统将会开启蓝牙设备,该过程完成(或失败)后,将会回到你的应用程序。
Set pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "n" + device.getAddress());
}
}
需要使用BluetoothDevice进行连接实例化的唯一值是MAC地址。在上述的例子中,该部分作为ArrayAdapter的一部分呈现给用户。关于如何使用MAC地址实例化连接,请参考后文。
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy