蓝牙
简介
Bluetooth是目前使用的最广泛的无线通讯协议。主要针对短距离设备通讯(10M)。
常用于连接耳机,连接其他手机,电脑等。
相关的API
BluetoothAdapter:该类的对象代表了本地的蓝牙适配器。
BluetoothDevice:代表了一个远程的Bluetooth设备。
蓝牙设备扫描
权限声明
在AndroidManifest.xml声明蓝牙权限:
<user-permission android:name=”android.permission.BLUETOOTH” />
代码实现
//获得BluetoothAdapter对象
BluetoothAdapter adapter =BluetoothAdapter.getDefaultAdapter();
//判断是否拥有蓝牙
if (adapter == null) {
System.out.println("Device does not support Bluetooth"); //没有蓝牙
} else {
System.out.println("Device support Bluetooth"); //有蓝牙
//在有蓝牙的情况下,判断蓝牙是否打开
if (!adapter.isEnabled()) {
System.out.println("notEnable"); //没有打开
Intent intent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE) ;
startActivity(intent) ;
} else {
System.out.println("isEnable"); //已打开
}
//扫描所有蓝牙设备,得到的远程设备,存放在set集合中。
Set<BluetoothDevice> set = adapter.getBondedDevices();
if (set.size() > 0) {
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next();
//输出设备的名字和MAC地址。
System.out.println(bluetoothDevice.getName()
+"---"+bluetoothDevice.getAddress());
}
}
}
设置蓝牙的可见性
权限声明:
<user-permission android:name=” android.permission.BLUETOOTH_ADMIN”/>
代码部分
Intent disIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE) ;
//当超过300秒的时候,默认覆盖为300秒
disIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500) ;
startActivity(disIntent);