我目前正在开发一款安卓应用程序。当应用程序正在运行时,我需要通知用户设备的蓝牙已关闭。
如何通知远程设备蓝牙已关闭?
使用意图操作BluetoothAdapter.ACTION_STATE_CHANGED
注册BroadcastReceiver,并将您的通知代码移入onReceive
方法中。不要忘记检查新状态是否为OFF。
if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
== BluetoothAdapter.STATE_OFF)
// Bluetooth was disconnected
}
如果您想检测用户何时断开了他的蓝牙连接,并在稍后检测用户何时蓝牙已断开连接,则应按照以下步骤操作:
1) 获取用户BluetoothAdapter:
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
2) 创建并配置您的接收器,代码如下:
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 注册到 Activity 中:
this.registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));