【问题标题】:notification if the Bluetooth is turned off in android app如果蓝牙在 Android 应用程序中关闭,则通知
【发布时间】:2011-03-22 08:37:11
【问题描述】:

我目前正在开发一个 android 应用程序.. 每当蓝牙出现时,我都必须通知用户 设备的关闭,而应用程序是 目前正在运行.. 如何通知远程设备 tat BT is 关掉? 提前致谢

【问题讨论】:

  • 离题评论,因为这里没有 PM 系统:请停止在您编辑的帖子中添加噪音。您在帖子中添加了无用的粗体字,这不是一件好事。欢迎您的编辑,只是没有这种无用和烦人的噪音。

标签: android bluetooth


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果您想检测用户何时断开蓝牙,然后再检测用户何时断开蓝牙,您应该执行以下步骤:

    1) 获取用户蓝牙适配器:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      相关资源
      最近更新 更多