我目前正在开发一个Android应用程序.. 我必须在蓝牙时通知用户 当应用程序关闭时,设备关闭 正在运行.. 如何通知BT BT的远程设备 关掉? 提前致谢
答案 0 :(得分:25)
使用意图操作BluetoothAdapter.ACTION_STATE_CHANGED
注册 BroadcastReceiver ,并将您的notifiyng代码移至onReceive
方法。不要忘记检查新状态是否关闭
if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
== BluetoothAdapter.STATE_OFF)
// Bluetooth was disconnected
}
答案 1 :(得分:11)
如果您想检测用户何时断开其蓝牙连接,稍后检测用户何时将蓝牙断开连接,您应该执行以下步骤:
1)获取用户BluetoothAdapter:
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
2)创建和配置您的Receiver,代码如下:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// It means the user has changed his bluetooth state.
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
if (btAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
// The user bluetooth is turning off yet, but it is not disabled yet.
return;
}
if (btAdapter.getState() == BluetoothAdapter.STATE_OFF) {
// The user bluetooth is already disabled.
return;
}
}
}
};
3)将您的BroadcastReceiver注册到您的活动中:
this.registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));