Android蓝牙 打开 关闭 与 搜索
1.获取权限
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
//普通权限,操作蓝牙时需要
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
//高级权限,配对等操作时需要
</manifest>
2.打开和关闭蓝牙设备
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="打开蓝牙"
android:onClick="openBlueTooth"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭蓝牙"
android:onClick="closeBlueTooth"/>
public void openBlueTooth(View view){
// 打开蓝牙(提示对话框)
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
// 打开蓝牙(静默,无提示)
// BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// bluetoothAdapter.enable();//需要BLUETOOTH_ADMIN权限
}
public void closeBlueTooth(View view){
// 关闭蓝牙
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.disable();
}
3.搜索蓝牙设备
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="搜索蓝牙"
android:onClick="scanBlueTooth"/>
public void scanBlueTooth(View view){
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
// 返回值是个BluetoothDevice的Set集合
Set<BluetoothDevice> bluetoothDevices = bluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : bluetoothDevices){
System.out.println("Name: " + device.getName());
System.out.println("Address: " + device.getAddress());
}
}