【问题标题】:Android Bluetooth detect when device is connected issueAndroid蓝牙检测设备何时连接问题
【发布时间】:2016-12-28 20:04:00
【问题描述】:

我目前正在制作一个根据您连接的蓝牙设备调整音量的应用。

我想改变音乐音量时遇到问题

我的应用程序检测到何时连接了蓝牙设备,它可以改变音量,但感觉太快了

以下是部分代码:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice d = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            deviceConnected(d);
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            deviceDisconnected(d);
        }
    }
};

private void deviceConnected(BluetoothDevice bluetoothDevice) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean showToasts = prefs.getBoolean("show_toasts", false);
    if (showToasts) { Toast.makeText(this, getResources().getString(R.string.connected_to) + " " + bluetoothDevice.getName(), Toast.LENGTH_SHORT).show(); }

    mDeviceDAO = new DeviceDAO(this);
    mDeviceDAO.open();

    DeviceOptions device = mDeviceDAO.select(bluetoothDevice.getAddress());
    if (device == null) { return; }

    if(device.getActivated() == 0) {
        return;
    }

    int v = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    saveLastVolume(v);

    int volume = device.getVolume();

    int flag = 0;
    if(prefs.getBoolean("show_am_ui", false)) {
        flag = AudioManager.FLAG_SHOW_UI;
    }
    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
            volume,
            flag);
}

如果在我更改音量时添加大约 3000 毫秒的延迟,它会正常工作,但它不是一个干净的解决方案。事实上,在蓝牙设备“完全”连接之前,会显示连接的 toast

我还发现了一个做同样事情的应用程序,但我似乎在做同样的事情。

Here is its githublink

【问题讨论】:

    标签: java android bluetooth


    【解决方案1】:

    您捕获的是ACL connectedACL disconnected,是的,一旦您的吐司出现,您就是对的,即 ACL 连接并不意味着蓝牙配置文件已连接(正是您所说的“完全”连接),它仅表示在两台设备之间建立物理连接,您不妨接收其他事件,例如HFP/A2dp 已连接,这才是真正连接的配置文件。

    然而ACL disconnected是蓝牙连接真正断开的里程碑。

    【讨论】:

    • 感谢您提供的遮阳篷,我做了一些研究,找到了“BluetoothA2dp”类,其中有 getConnectionState 函数可以帮助我。但我需要一个监听器来检测变化,但我找不到注意事项。
    • 你也可以参考BluetoothHeadset的ACTION_CONNECTION_STATE_CHANGED。这也是 Android 上最常用的配置文件连接的参考。
    • 感谢您的支持,我终于设法通过听 BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED(用于连接)和 BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED(断开连接时)来做到这一点
    • A2DP链接一直建立就好了;并且音频流将始终打开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    相关资源
    最近更新 更多