蓝牙与设备的连接与自动适配

蓝牙与设备进行自动适配:

 

与设备连接时一般通过广播BroadcastReceiver来实现,但是为了实现蓝夜与设备的自动适配,我们需要自定义一个广播,

 

public class PairingRequest extends BroadcastReceiver {
    String strPsw = "1234";  //适配码
    final String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST"; //与配置文件中注册的广播的action name匹配

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_PAIRING_REQUEST)) { //自定义广播的目的所在
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                try {
                    abortBroadcast(); //终止广播
                    ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
                    
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(context, "请求连接错误...", 1000).show();
                }
            }
        }
    }
}
然后在配置文件中注册广播并设置优先级priority,与自定义广播中的abortBroadcast()方法相呼应,结合使用可以取消在自动适配时
一闪而出的配对框:
<!-- 这个权限用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"> 
<receiver android:name=".activitys.zice.PairingRequest">
    <intent-filter android:priority="1000">
        <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
    </intent-filter>
</receiver>
在Activity中使用:
private BluetoothDevice buletoothdevice;
private static String name = "BT";
private String address; //要连接的目标蓝牙设备的MAC地址
//这条是蓝牙串口通用的UUID,不要更改
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private boolean isBonded = false;
private Timer timer;  //判断蓝牙是否连接
private TimerTask timerTask;
public IntentFilter filter = null; //定义广播接收
    private PairingRequest mReceiver = new PairingRequest() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BluetoothDevice.ACTION_FOUND:  //发现蓝牙
                    buletoothdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (buletoothdevice.getName() != null) {
                        if (buletoothdevice.getName().equals(name)) { //name:自定义设备名称
                            address = buletoothdevice.getAddress();
//                            创建连接
                            new ConnectTask().execute(address);
                        }
                    }
                    break;
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:  //查看配对状态
                    buletoothdevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    switch (buletoothdevice.getBondState()) {
                        case BluetoothDevice.BOND_BONDING:
                            Log.i("BloodPressure", "正在配对");
                        case BluetoothDevice.BOND_BONDED:
                            unregisterReceiverS(mReceiver); //解注册
                            Log.i("BloodPressure", "配对结束");
                        case BluetoothDevice.BOND_NONE:
                            Log.i("BloodPressure", "取消配对");
                    }
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:  //查找结束
                    break;

            }
        }
    };

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_pressure_result);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        InitBluetooth();

        filter = new IntentFilter();  //添加广播接收的action
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        timer = new Timer();
        timerTask = new TimerTask() {  //用来判断是否已配对
            @Override
            public void run() {
                if (mBluetoothAdapter.isEnabled()) {
                    timerTask.cancel();
                    timer.cancel();
                    //搜索已配对的设备
                    Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
                    for (BluetoothDevice device : devices) {
                        if (device.getName().equals(name)) {
                            isBonded = true;
                            buletoothdevice = device;
                        }
                    }
                    if (isBonded) {
                        address = buletoothdevice.getAddress();
                        //创建连接
                        new ConnectTask().execute(address);
                    } else {
                        registerReceiver(mReceiver, filter);   //注册广播
                        mBluetoothAdapter.startDiscovery();
                    }
                }
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

public void InitBluetooth() //得到一个蓝牙适配器 BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE) mBluetoothAdapter = bluetoothManager.getAdapter() if (mBluetoothAdapter == null) Toast.makeText(this, "你的手机不支持蓝牙", Toast.LENGTH_SHORT).show()finish()return;
}//判断蓝牙是否打开if (!mBluetoothAdapter.isEnabled()) { mBluetoothAdapter.enable() }}public void unregisterReceiverS(BroadcastReceiver receiver) {unregisterReceiver(receiver) if (mBluetoothAdapter != null) { mBluetoothAdapter.cancelDiscovery();}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值