服务端使用实例
请求检测权限,启动服务监听
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)
}
}