之前做的藍牙自動配對,現在整理一下。免得忘記。
首頁一定要注意權限問題
<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("----連接成功-----");
}
至此,手機藍牙設備與遠程藍牙設備自動配對連接成功。