一般情况下用默认的蓝牙适配器就好了
private static BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
贴几个常用的方法
/**
* 打开蓝牙功能
*/
public static void openBluetooth() {
adapter.enable();
}
/**
* 关闭蓝牙功能
*/
public static void closeBluetooth() {
adapter.disable();
}
/**
* 蓝牙是否打开
* @return
*/
public static boolean isBluetoothOpen(){
return adapter.isEnabled();
}
用广播接收扫描到的设备 然后用Handle将信息发送出去
IntentFilter filter=new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.setPriority(Integer.MAX_VALUE);
registerReceiver(receiver,filter);
public class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice bluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetoothDevice.getBondState()!=BluetoothDevice.BOND_BONDED){
Message msg=new Message();
msg.what=1;
msg.obj=new com.hiep.pump.model.BluetoothDevice(bluetoothDevice.getName(),bluetoothDevice.getAddress());
DeviceListDialog.getHandler().sendMessage(msg);
}
if (bluetoothDevice.getBondState()==BluetoothDevice.BOND_BONDED){
Message msg=new Message();
msg.what=2;
msg.obj=new com.hiep.pump.model.BluetoothDevice(bluetoothDevice.getName(),bluetoothDevice.getAddress());
DeviceListDialog.getHandler().sendMessage(msg);
}
}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
Message msg=new Message();
msg.what=0;
msg.obj="discovery finished";
DeviceListDialog.getHandler().sendMessage(msg);
}
}
}
拿到蓝牙地址后 通过反射进行蓝牙配对
android.bluetooth.BluetoothDevice btDev = bluetoothadapter.getRemoteDevice(list.get(position).getAddress());
if (btDev.getBondState() == android.bluetooth.BluetoothDevice.BOND_NONE) {
try {
Log.i("BlueToothTestActivity", "开始配对");
Method createBondMethod = android.bluetooth.BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(btDev);
} catch (Exception e) {
e.printStackTrace();
}
}else if(btDev.getBondState() == android.bluetooth.BluetoothDevice.BOND_BONDED){
connect(btDev);
}