Android 获取蓝牙列表,连接并发送数据

2023-02-11 08:28:49

今天分享一个获取蓝牙列表,连接并传输数据的功能

class BlueToothActivity : BaseActivity(), ICBlueTooth.IVBlueTooth{

    override val layout = R.layout.a_bluetooth
    var strData = ""
    private var mBluetoothGatt: BluetoothGatt? = null
    private var device: BleDevice? = null
    private lateinit var versionPresenter: VersionPresenter

    //服务和特征值
    private var writeUuidService: UUID? = null
    private var writeUuidChara: UUID? = null
    private lateinit var mView: ICBlueTooth.IVBlueTooth
    private lateinit var mContext: Context
    override fun initView() {
        mView = this
        mContext = this
    }

 
    override fun initEvent() {
        ll_start.setOnClickListener {
            startScan()
        }
        ll_data.setOnClickListener {
            if (writeUuidService == null || writeUuidChara == null || device == null) {
                ToastUtils.showShort("请连接蓝牙")
                return@setOnClickListener
            }
            strData = ""
            showLoading("获取数据...")
            val service = mBluetoothGatt!!.getService(writeUuidService)
            val charaWrite = service.getCharacteristic(writeUuidChara)

            BleManager.getInstance().write(
                device,
                charaWrite.service.uuid.toString(),
                charaWrite.uuid.toString(),
                HexUtil.hexStringToBytes("010301820010E5D2"),//A5010b020300040300b278  010301820006641C
                writeCallback
            )

            BleManager.getInstance().notify(
                device,
                charaWrite.service.uuid.toString(),
                charaWrite.uuid.toString(),
                notifyCallback
            )
        }

    }

    private fun startScan() {

        BleManager.getInstance().scan(object : BleScanCallback() {
            override fun onScanFinished(scanResultList: MutableList<BleDevice>) {
                dims()
                val array = ArrayList<BleDevice>()
                if (device != null) {
                    array.add(device!!)
                }
             
                BlueToothDialog.start(mContext, array, mView)
            }

            override fun onScanStarted(success: Boolean) {
                showLoading("正在搜索蓝牙")
            }

            override fun onScanning(bleDevice: BleDevice?) {

            }

        })
    }


    private val writeCallback: BleWriteCallback = object : BleWriteCallback() {
        override fun onWriteSuccess(
            current: Int,
            total: Int,
            justWrite: ByteArray
        ) {
            runOnUiThread {
                //ToastUtils.showShort("写入成功")
            }
        }

        override fun onWriteFailure(exception: BleException) {
            runOnUiThread {
                dims()
                ToastUtils.showShort("获取失败,请重新获取")
            }
        }
    }
    private val notifyCallback: BleNotifyCallback = object : BleNotifyCallback() {
        override fun onNotifySuccess() {
            //接收成功
            runOnUiThread {
                //ToastUtils.showShort("接收成功")
            }
        }

        override fun onNotifyFailure(exception: BleException) {
            runOnUiThread {
                dims()
                ToastUtils.showShort("获取失败,请重新获取")
            }
        }

        @SuppressLint("SetTextI18n")
        override fun onCharacteristicChanged(data: ByteArray) {
            runOnUiThread {
                val str = Utils.bytesToHexString(data)
                strData += str
                Log.i("1234", "返回数据" + str + "返回数据长度" + str.length)
               
                dims()
            }
        }

    }

    @SuppressLint("SetTextI18n")
    override fun result(
        device: BleDevice,
        mBluetoothGatt: BluetoothGatt,
        writeUuidService: UUID,
        writeUuidChara: UUID
    ) {
        this.device = device
        this.mBluetoothGatt = mBluetoothGatt
        this.writeUuidChara = writeUuidChara
        this.writeUuidService = writeUuidService
        tv_name.text = device.name + "\n" + device.mac
        tv_stats.text = "蓝牙已连接"
    }



    override fun showError(msg: String) {
        showToast(msg)
    }
}
class BlueToothDialog : BaseDialog() {

    override val layout = R.layout.g_bluetooth

    private var mAdapter = DeviceListAdapter()
    private lateinit var mBluetoothGatt: BluetoothGatt
    private lateinit var device: BleDevice

    //服务和特征值
    private var writeUuidService: UUID? = null
    private var writeUuidChara: UUID? = null
    private var readUuidService: UUID? = null
    private var readUuidChara: UUID? = null
    private var notifyUuidService: UUID? = null
    private var notifyUuidChara: UUID? = null
    private var indicateUuidService: UUID? = null
    private var indicateUuidChara: UUID? = null

    companion object {

        lateinit var mView: ICBlueTooth.IVBlueTooth
        lateinit var mContext: Context
        lateinit var scanResultList: MutableList<BleDevice>
        fun start(
            mContext: Context,
            scanResultList: MutableList<BleDevice>,
            mView: ICBlueTooth.IVBlueTooth
        ) {
            this.mContext = mContext
            this.mView = mView
            this.scanResultList = scanResultList
            val taskDialog = BlueToothDialog()
            taskDialog.show((mContext as BaseActivity).supportFragmentManager, "")

        }

    }

    override fun onStart() {
        super.onStart()
        mWindow.setGravity(Gravity.CENTER)
        mWindow.setWindowAnimations(R.style.MyDialog)
        mWindow.setLayout(
            (ScreenUtils.getScreenWidth() * 0.70).toInt(),
            (ScreenUtils.getScreenHeight() * 0.50).toInt()
        )
    }


    override fun initView() {
        Utils.setRecyclerView(recycler_view, mContext)
        recycler_view.adapter = mAdapter
        mAdapter.setNewData(scanResultList)


    }

    override fun initEvent() {
        mAdapter.onItemClickListener =
            BaseQuickAdapter.OnItemClickListener { _, _, position ->
                mBluetoothGatt =
                    BleManager.getInstance().connect(mAdapter.data[position], mCallback)
            }

    }

    private val mCallback: BleGattCallback = object : BleGattCallback() {
        override fun onStartConnect() {
            ToastUtils.showShort("开始连接")
        }

        override fun onConnectFail(bleDevice: BleDevice, exception: BleException) {
            ToastUtils.showShort("连接失败")
        }

        override fun onConnectSuccess(
            bleDevice: BleDevice,
            gatt: BluetoothGatt,
            status: Int
        ) {
            ToastUtils.showShort("连接成功")
            device = bleDevice
            //发现服务
            initServiceAndChara()
            //订阅通知
            if (notifyUuidService == null || notifyUuidChara == null) {
                ToastUtils.showShort("连接失败,请重新连接")
                return
            }

            mBluetoothGatt.setCharacteristicNotification(
                mBluetoothGatt
                    .getService(notifyUuidService).getCharacteristic(notifyUuidChara), true
            )
            writeUuidService?.let {
                writeUuidChara?.let { it1 ->
                    mView.result(
                        device, mBluetoothGatt, it,
                        it1
                    )
                }
            }


            dismiss()
        }

        override fun onDisConnected(
            isActiveDisConnected: Boolean,
            bleDevice: BleDevice,
            gatt: BluetoothGatt,
            status: Int
        ) {
            ToastUtils.showShort("断开连接")
        }

    }

    private fun initServiceAndChara() {
        val bluetoothGattServices = mBluetoothGatt.services
        for (bluetoothGattService in bluetoothGattServices) {
            val characteristics =
                bluetoothGattService.characteristics
            for (characteristic in characteristics) {
                val charaProp = characteristic.properties
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_READ > 0) {
                    readUuidChara = characteristic.uuid
                    readUuidService = bluetoothGattService.uuid
                }
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_WRITE > 0) {
                    writeUuidChara = characteristic.uuid
                    writeUuidService = bluetoothGattService.uuid

                }
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE > 0) {
                    writeUuidChara = characteristic.uuid
                    writeUuidService = bluetoothGattService.uuid
                }
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_NOTIFY > 0) {
                    notifyUuidChara = characteristic.uuid
                    notifyUuidService = bluetoothGattService.uuid
                }
                if (charaProp and BluetoothGattCharacteristic.PROPERTY_INDICATE > 0) {
                    indicateUuidChara = characteristic.uuid
                    indicateUuidService = bluetoothGattService.uuid
                }
            }
        }
    }
}
interface ICBlueTooth {

    interface IVBlueTooth : BaseView {
        fun result(
            device: BleDevice,
            mBluetoothGatt: BluetoothGatt,
            writeUuidService: UUID,
            writeUuidChara: UUID
        ) {}
    }
}
  • 作者:森森先生666
  • 原文链接:https://blog.csdn.net/qq_28643195/article/details/109751341
    更新时间:2023-02-11 08:28:49