Android应用程序中蓝牙关闭的通知

18

我目前正在开发一款安卓应用程序。当应用程序正在运行时,我需要通知用户设备的蓝牙已关闭。

如何通知远程设备蓝牙已关闭?


离题评论:这里没有私信系统,请停止在编辑帖子时添加噪音。您正在向帖子中添加无用的粗体字,这不是一件好事。欢迎您的编辑,但请不要添加这种无用和令人烦恼的噪音。 - Shadow The Spring Wizard
2个回答

26

使用意图操作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
}

20

如果您想检测用户何时断开了他的蓝牙连接,并在稍后检测用户何时蓝牙已断开连接,则应按照以下步骤操作:

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));    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接