第一步 声明蓝牙权限
一、要在应用程序中使用蓝牙功能,必须声明蓝牙的使用权限:BLUETOOTH和BLUETOOTH_ADMIN
1、BLUETOOTH
必须请求BLUETOOTH权限才能够使用蓝牙通信,进而请求连接、接收连接、传输数据
2、BLUETOOTH_ADMIN
必须请求BLUETOOTH_ADMIN才能够初始化device discovery或者管理蓝牙设置(Bluetooth settings)。
大多数应用程序必须具有这个权限才能够发现本地蓝牙设备,这个权限保护的其他能力(除了发现本地设备)不应该被使用,除非你的应用程序是在用户请求的时候能够修改蓝牙设置的管理者。
二、注意:如果你想要使用BLUETOOTH_ADMIN权限,那么你首先必须有BLUETOOTH权限。
三、在AndroidManifest文件中声明程序的蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
第二步 获取本地的蓝牙设备-BluetoothAdapter
任何蓝牙activity都需要BluetoothAdapter类。使用静态方法getDefaultAdapter()获得一个BluetoothAdapter的实例,这代表了设备本身的蓝牙适配器(the Bluetooth radio)。整个系统只有一个蓝牙适配器,你的程序可以通过获取到BluetoothAdapter实例与之交互。如果getDefaultAdapter()方法返回null则说明你的设备不支持蓝牙。
实例代码如下:
BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();//判断BluetoothAdapter对象是否为空,如果为空,则表明本机没有蓝牙设备
if(adapter !=null){
System.out.println("本机拥有蓝牙设备");
}
else{
System.out.