У меня есть функция, которая включает Bluetooth
в фоновом режиме и собирает информацию о ближайших устройствах. Это для удаленного приложения Healthcare и для того, чтобы знать, находится ли человек в людном месте. Функция Bluetooth
отлично работает, когда я устанавливаю приложение, подключив устройство к Android studio, но не когда я создаю и устанавливаю apk (как для отладки, так и для выпуска). Любая потенциальная причина такого поведения? Все переменные инициализированы. Этот Executable
вызывается каждый час.
class Bluetooth(private val context: Context): Executable {
private val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
private val deviceReceiver = DeviceReceiver()
private val turnedOnReceiver = TurnedOnReceiver()
private val logger = Logger(
context,
TableFormat(
"bluetooth",
Text("id"),
Text("deviceName"),
Text("deviceAdress"),
Text("bluetoothClass"),
Integer("bondState"),
Integer("type")
)
)
override fun execute() {
Log.d(TAG, "execute")
if (devicedSupportsBluetooth()) {
Log.d(TAG, "has bluetooth")
registerDeviceReceiver()
if(isBluetoothDisabled()) {
Log.d(TAG, "isDisabled")
turnBlueToothOnAndDiscover()
}
else {
Log.d(TAG, "isEnabled")
discover()
}
}
}
private fun devicedSupportsBluetooth(): Boolean {
return bluetoothAdapter != null
}
private fun isBluetoothDisabled(): Boolean {
return !bluetoothAdapter.isEnabled
}
private fun disableBluetooth() {
bluetoothAdapter.disable()
}
private fun discover() {
Log.d(TAG, "discover")
bluetoothAdapter.startDiscovery()
}
private fun registerDeviceReceiver() {
deviceReceiver.turnOffAfterDiscovery = isBluetoothDisabled()
val intentFilter = IntentFilter()
intentFilter.addAction(BluetoothDevice.ACTION_FOUND)
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
context.registerReceiver(deviceReceiver, intentFilter)
}
private fun registerTurnedOnReceiver() {
val intentFilter = IntentFilter()
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
context.registerReceiver(turnedOnReceiver, intentFilter)
}
private fun turnBlueToothOnAndDiscover() {
registerTurnedOnReceiver()
bluetoothAdapter.enable()
}
private inner class TurnedOnReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "TurnedOnReceiver onReceive " + intent.action)
val newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
when (newState) {
BluetoothAdapter.STATE_ON -> {
context.unregisterReceiver(this)
discover()
}
}
}
}
private inner class DeviceReceiver: BroadcastReceiver() {
var turnOffAfterDiscovery = false
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "DeviceReceiver onReceive " + intent.action)
when (intent.action) {
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> close()
BluetoothDevice.ACTION_FOUND -> storeDeviceDataInDatabase(intent)
}
}
private fun close() {
context.unregisterReceiver(this)
if (turnOffAfterDiscovery) {
disableBluetooth()
}
}
private fun storeDeviceDataInDatabase(intent: Intent) {
var id = ""
var name = ""
var address = ""
var devClass = ""
var bondState = ""
var type = ""
val device = getDevice(intent)
if(device != null){
id = device.hashCode().toString()
if (device.name != null) {
name = device.name
}
if (device.address != null) {
address = device.address
}
if (device.bluetoothClass != null) {
devClass = device.bluetoothClass.toString()
}
if (device.bondState != null) {
bondState = device.bondState.toString()
}
if (device.type != null && Build.VERSION.SDK_INT >= 18) {
type = device.type.toString()
}
}
logger.save(
id,
name,
address,
devClass.toString(),
bondState,
type
)
}
private fun getDevice(intent: Intent): BluetoothDevice {
return intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)!!
}
}
}