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