Android中的蓝牙


蓝牙
蓝牙主要针对短距离设备通信(10米以内)
Android.bluetooth包中
1.BluetoothAdapter:代表本地的蓝牙适配器
2.BluetoothDevice:代表一个远程的Bluetooth设备

1.
在AndroidManifest.xml声明蓝牙权限:
<uses-permission 

android:name="android.permission.BLUETOOTH"/>

2.一般过程
(1)获得BluetoothAdapter对象;
(2)判断当前设备是否拥有蓝牙设备;
(3)判断当前设备中的蓝牙设备是否已经打开;

(4)得到所有已经配对的蓝牙设备对象;

  1. //获得本地适配器对象   
  2.             BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();  
  3.             //是否有蓝牙设备   
  4.             if (adapter != null) {  
  5.                 System.out.println("get a bluetooth!");  
  6.                 //打开蓝牙设备   
  7.                 if (!adapter.isEnabled()) {  
  8.                     Intent intent = new Intent(  
  9.                             BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  10.                     startActivity(intent);  
  11.                 }  
  12.                 Set<BluetoothDevice> devices = adapter.getBondedDevices();  
  13.                 //获得已绑定的设备   
  14.                 if(devices.size()>0){  
  15.                     for (BluetoothDevice bluetoothDevice : devices) {  
  16.                         System.out.println(bluetoothDevice.getName()+"  "+bluetoothDevice.getAddress());  
  17.                     }  
  18.                 }  
  19.                 else{  
  20.                     System.out.println("no bonded device");  
  21.                 }  
  22.               
  23.   
  24.             }  
  25.             else{  
  26.                 System.out.println("no bluetooth device");  
  27.             }  

可见性设置

  1. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);  
  2.             discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);  
  3.             startActivity(discoverableIntent);  
持续时间不能超过300秒,超过的一律将变成300s

开始扫描

  1. adapter.startDiscovery();  

相关内容