2016-08-22 69 views
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的延迟,它会正常工作,但它不是一个干净的解决方案。事实上,连接的祝酒会在蓝牙设备“完全”连接之前显示。

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

Here is its githublink

回答

0

什么是你的捕捉是ACL connectedACL disconnected,是的,你是对的,一旦你的面包出现即连接并不意味着连接蓝牙配置文件(你说什么“完全”连接)的ACL,它仅意味着两个设备之间建立的物理连接,您可能还会接收其他事件,例如HFP/A2dp连接,这是连接的真实配置文件。

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

+0

谢谢你的awnser,我做了一些研究,并且发现了类“BluetoothA2dp”,这里有getConnectionState函数可以帮助我。但我需要一个侦听器来检测变化,但我找不到注意。 –

+0

你也可以参考'BluetoothHeadset'的ACTION_CONNECTION_STATE_CHANGED。这也是Android上最常用的配置文件连接的参考。 –

+0

谢谢你的awnsers,我最终设法通过监听BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED(用于连接)和BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED(当它断开连接时) –