0
我目前正在制作一个根据您连接的蓝牙设备调整音量的应用程序。设备连接时的Android蓝牙检测问题
我有问题,当我想改变音乐的音量
当一个蓝牙设备连接我的应用程序检测,它可以改变音量,但它像它去得太快
这里是一些代码:
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);
}
如果当我改变音量周围添加3000ms的延迟,它会正常工作,但它不是一个干净的解决方案。事实上,连接的祝酒会在蓝牙设备“完全”连接之前显示。
我还发现一个应用程序可以做同样的事情,但似乎我正在做同样的事情。
谢谢你的awnser,我做了一些研究,并且发现了类“BluetoothA2dp”,这里有getConnectionState函数可以帮助我。但我需要一个侦听器来检测变化,但我找不到注意。 –
你也可以参考'BluetoothHeadset'的ACTION_CONNECTION_STATE_CHANGED。这也是Android上最常用的配置文件连接的参考。 –
谢谢你的awnsers,我最终设法通过监听BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED(用于连接)和BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED(当它断开连接时) –