在我的应用中,我正在尝试对我的设备的蓝牙(BT)被禁用时的情况作出反应。但是,当连接到我的手机的其他设备断开或关闭时,似乎会报告ACTION_BOND_STATE_CHANGED(检查this和this答案),至少在我的情况下。如果我注册ACTION_ACL_DISCONNECTED然后关闭我的设备BT,则调用onReceive()。
init {
fetchDevices()
val mBTPairedReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
val device = intent.getParcelableExtra<Parcelable>(BluetoothDevice.EXTRA_DEVICE)
val previousStates = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothAdapter.ERROR)
val states = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothAdapter.ERROR)
when (action) {
BluetoothDevice.ACTION_FOUND -> if (device != null) {
fetchDevices()
deviceListener?.let { it(devices) }
}
BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
when (states) {
BluetoothAdapter.STATE_TURNING_OFF -> {
Log.d("MESSAGE", "BT is turning OFF")
}
BluetoothAdapter.STATE_ON -> Log.d("MESSAGE", "BT is ON now")
}
}
}
}
}
application.registerReceiver(mBTPairedReceiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED))
}
我想知道我的设备上是否要关闭/关闭BT,以便在丢失连接之前将最终消息发送到我连接的另一台设备。
答案 0 :(得分:0)
用户广播接收器
private final BroadcastReceiver btReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(btAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, btAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "btReceiver: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "btReceiver: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "btReceiver: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "btReceiver: STATE TURNING ON");
break;
}
}
}
};