RxJava Android Bluetooth SDK 经典蓝牙服务端使用实例

服务端使用实例

请求检测权限,启动服务监听
class MasterActivity : AppCompatActivity() {

    private var bluetoothManager: BluetoothServerManger? = null

    companion object {
        const val TAG: String = "MasterActivity"
    }

    private lateinit var searchDeviceLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_master)

        searchDeviceLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            bluetoothManager!!.startAdvertiser()
        }
        startLis()
    }

    private fun startLis() {
        bluetoothManager = BluetoothServerManger(this)
        bluetoothManager!!.registerEvent()
        bluetoothManager!!.let {
            if (!it.bluetoothEnable()) {
                Log.i(TAG, "蓝牙不可用")
                return
            }
            if (!it.bluetoothIsOpen()) {
                Log.i(TAG, "蓝牙未开启")
                return
            }
            // 权限
            if (it.havePermission()) {
                startDiscoverable()
            } else {
                requestBTPermissions()
            }
        }
    }

    /**
     * 请求权限
     */
    private fun requestBTPermissions() {
        // 扫描权限请求
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), 10086);
        } else {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN), 10086);
        }
    }

    /**
     * 权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 10086 && grantResults.sum() == 0) {
            startDiscoverable()
        }
    }

    private fun startDiscoverable() {
        var requestDiscoverIntent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE)
        requestDiscoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0)
        searchDeviceLauncher.launch(requestDiscoverIntent)
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容