之前做的蓝牙自动配对,现在整理一下。免得忘记。
首页一定要注意权限问题
1. <uses-permission android:name="android.permission.BLUETOOTH" /> //使用蓝牙的权限
2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> //管理蓝牙的权限
另外要注意一点 模拟器不能模拟蓝牙设备。
为了使手机的蓝牙设备 自动与 远程蓝牙设备 配对。
步骤为:
1.获得手机蓝牙的适配器
1. BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
2.检查手机的蓝牙设备是否打开,未打开则 强制 打开蓝牙设备
1. <span style="color:#000000;">public static void openBluetooth(){
2. if(adapter != null){
3. if(!adapter.isEnabled()){
4. //强制开启蓝牙
5. }
6. }
7. }</span>
3.获得给定地址的远程蓝牙设备
1. BluetoothDevice device = adapter.getRemoteDevice(strAddress);
4.检查远程蓝牙设备是否已经配对,若没配对则进行配对
1. if(device.getBondState() != BluetoothDevice.BOND_BONDED){//判断给定地址下的device是否已经配对
2. try{
3. //设置pin值
4. ClsUtils.createBond(device.getClass(), device);
5. remoteDevice = device;
6. }
7. catch (Exception e) {
8. // TODO: handle exception
9. "配对不成功");
10. }
11. }
12. else {
13. remoteDevice = device;
14. }
15.
16. //自动配对设置Pin值
17. static public boolean autoBond(Class btClass,BluetoothDevice device,String strPin) throws Exception {
18. "setPin",new Class[]{byte[].class});
19. new Object[]{strPin.getBytes()});
20. return result;
21. }
22.
23. //开始配对
24. static public boolean createBond(Class btClass,BluetoothDevice device) throws Exception {
25. "createBond");
26. Boolean returnValue = (Boolean) createBondMethod.invoke(device);
27. return returnValue.booleanValue();
28. }
因为在SDK 中没有 autoBond和createBond方法,所以需要用Java的反射机制去调用这两个函数。
这里可以用反射机制枚举BluetoothDevice的所以方法和常量
1. static public void printAllInform(Class clsShow) {
2. try {
3. // 取得所有方法
4. Method[] hideMethod = clsShow.getMethods();
5. int i = 0;
6. for (i; i < hideMethod.length; i++) {
7. "method name", hideMethod[i].getName());
8. }
9. // 取得所有常量
10. Field[] allFields = clsShow.getFields();
11. for (i = 0; i < allFields.length; i++) {
12. "Field name", allFields[i].getName());
13. }
14. catch (SecurityException e) {
15. // throw new RuntimeException(e.getMessage());
16. e.printStackTrace();
17. catch (IllegalArgumentException e) {
18. // throw new RuntimeException(e.getMessage());
19. e.printStackTrace();
20. catch (Exception e) {
21. // TODO Auto-generated catch block
22. e.printStackTrace();
23. }
24. }
5.配对成功后,手机作为客户端建立一个BluetoothSocket类来连接远程设备,然后调用connect()方法去尝试一个面向远程设备的连接。
1. public static final String CONTENT_UUID = "00001101-0000-1000-8000-00805F9B34FB";
2. UUID uuid = UUID.fromString(Contents.CONTENT_UUID); //UUID表示串口服务
3. //客户端建立一个BluetoothSocket类去连接远程蓝牙设备
4. bluetoothSocket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
5. bluetoothSocket.connect();//尝试连接
6. inputStream = bluetoothSocket.getInputStream();//打开IO流
7. System.out.println("--inputStream------");
8. if(inputStream != null){
9. true;
10. "----连接成功-----");
11. }
至此,手机蓝牙设备与远程蓝牙设备自动配对连接成功。