蓝牙
蓝牙主要针对短距离设备通信(10米以内)
Android.bluetooth包中
1.BluetoothAdapter:代表本地的蓝牙适配器
2.BluetoothDevice:代表一个远程的Bluetooth设备
1.
在AndroidManifest.xml声明蓝牙权限:
<uses-permission
android:name="android.permission.BLUETOOTH"/>
2.一般过程
(1)获得BluetoothAdapter对象;
(2)判断当前设备是否拥有蓝牙设备;
(3)判断当前设备中的蓝牙设备是否已经打开;
(4)得到所有已经配对的蓝牙设备对象;
-
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-
- if (adapter != null) {
- System.out.println("get a bluetooth!");
-
- if (!adapter.isEnabled()) {
- Intent intent = new Intent(
- BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivity(intent);
- }
- Set<BluetoothDevice> devices = adapter.getBondedDevices();
-
- if(devices.size()>0){
- for (BluetoothDevice bluetoothDevice : devices) {
- System.out.println(bluetoothDevice.getName()+" "+bluetoothDevice.getAddress());
- }
- }
- else{
- System.out.println("no bonded device");
- }
-
-
- }
- else{
- System.out.println("no bluetooth device");
- }
可见性设置
- Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
- startActivity(discoverableIntent);
持续时间不能超过300秒,超过的一律将变成300s
开始扫描
- adapter.startDiscovery();