蓝牙项目

蓝牙后台连接

  1. 前台蓝牙服务和后台蓝牙服务—
    bindService和startService的区别
    startService只是简单启动服务,启用之后便无法控制,只能调用stopService停止。
    bindService使活动和服务进行通信。
    复写Service类中的onBinder()方法,返回要控制的binder对象。新建ServiceConnection,在其中拿到binder对象。然后进行操作,实现service和activity的通信。
    使用bindService进行绑定(intent connection auto)
    使用unbindService进行解绑(connection)

后台保持连接:在unbind之后立即startService(),同时使用一个常量记录当前连接状态。
当再进入这个界面时,需要进行判断,如果已连接,则不断开,未连接则连接。
在程序退出时,进行断开蓝牙连接服务。

扫描蓝牙设备

  1. 首先获取到BluetoothManager 通过其中的getAdapter()方法拿————————————到—————————————————————-BluetoothAdapter,然后通过BluetoothAdapter的startScan(LeScanCallback)的方法开始扫描设备。
  2. onLeScan(BluetoothDevice)就是我们扫描的设备。
  3. 使用BluetoothDevice.connectGatt()的方法进行连接,返回BluetoothGatt的实例,就可以进行相关读写数据操作了。

GATT

GATT(Generic Attribute Profile,普通属性协议),它使BLE设备通过Service和Characteristic进行通信。

代码实现蓝牙连接流程

  1. 初始化蓝牙相关信息
    首先判断是否支持蓝牙4.0BLE,需要安卓系统4.3以上才可以。
        final BluetoothManager bluetoothManager =
                (BluetoothManager) atyFrameworkActivity.getSystemService(Context.BLUETOOTH_SERVICE);
                //获取到蓝牙管理器
        mBluetoothAdapter = bluetoothManager.getAdapter();
        //通过蓝牙管理器获取到蓝牙适配器
  1. 通过bindService后获取到蓝牙服务,进行蓝牙搜索。在serviceConnection中开启蓝牙搜索
mBluetoothAdapter.startLeScan(mLeScanCallback);
//通过startLeScan进行搜索,实现蓝牙回调函数
在回调函数中,记录下搜索到的蓝牙地址
            public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                atyFrameworkActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "run()");
                        bluetoothDeviceAddressSet.add(device.getAddress());
                        bluetoothDevicesset.add(device);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值