2014-05-09 55 views
7

這裏有很多答案,我可以在BroadcastReceiver的幫助下建立連接的藍牙設備列表。現在我的問題是我怎麼知道哪個設備支持哪個配置文件。我希望能夠根據配置文件選擇設備,例如,獲取當前連接的設備及其配置文件的列表,並選擇其中一個。如果我有BluetoothDevice的實例,我不知道如何獲得這些信息。在Android中,如何獲取連接的藍牙設備的配置文件?

在此頁面上有一些代碼說明如何使用藍牙耳機配置文件:http://developer.android.com/guide/topics/connectivity/bluetooth.html#Profiles。但它不能解決我的問題。如果您認爲我錯過了任何東西,請幫助我並指出。

非常感謝。

回答

3

我遇到了同樣的問題。您似乎沒有從BluetoothDevice類中獲得可用的配置文件。 但周圍有很長的路要走通過從藍牙規範getDevicesMatchingConnectionStates方法得到的BluetoothDevice類列表

例如,如果你想找到這BluetoothDevice類的支持A2DP,首先創建一個自定義BluetoothProfile.ServiceListener

public class cServiceListener implements BluetoothProfile.ServiceListener { 
private static final int[] states={ BluetoothProfile.STATE_DISCONNECTING, 
            BluetoothProfile.STATE_DISCONNECTED, 
            BluetoothProfile.STATE_CONNECTED, 
            BluetoothProfile.STATE_CONNECTING}; 
@Override 
public void onServiceConnected(int profile, BluetoothProfile bluetoothProfile) { 
List<BluetoothDevice> Devices=bluetoothProfile.getDevicesMatchingConnectionStates(states); 
    for (BluetoothDevice loop:Devices){ 
     Log.i("myTag",loop.getName()); 
    } 
} 

@Override 
public void onServiceDisconnected(int profile) { 
} 

} 

然後將其連接到要檢查的配置文件,在這個例子中A2DP

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
cServiceListener mServiceListener=new cServiceListener(); 
mBluetoothAdapter.getProfileProxy(thisContext,mServiceListener, BluetoothProfile.A2DP); 

這將logcat的所有支持A2DP藍牙設備,其在請求的狀態。在這個例子中,它包括當前連接的所有設備和先前已斷開連接的設備。

0

查看Android源代碼,您可以通過查看其UUID來猜測設備可用的配置文件,然後逐個連接每個配置文件。

步驟0:複製_PROFILE_UUIDS從那裏常數:https://android.googlesource.com/platform/packages/apps/Settings/+/9ad703cdb9a8d0972c123b041d18aa7bbeb391a4/src/com/android/settings/bluetooth/LocalBluetoothProfileManager.java

第1步:讓你BluetoothDevice,通過掃描實例。確保它被妥善保管。

第2步:註冊BroadcastReceiverandroid.bluetooth.BluetoothDevice.ACTION_UUID行動意圖

第3步:您的設備上,調用fetchUuidsWithSdp方法

步驟4:您將收到一個ACTION_UUID廣播:在onReceive方法中,您可以取消註冊接收器,並獲得配置文件列表,如下所示:

ArrayList<Integer> profiles = new ArrayList<>(); 

ParcelUuid[] uuids = device.getUuids(); 

if (BluetoothUuid.containsAnyUuid(uuids, HEADSET_PROFILE_UUIDS)) 
{ 
    profiles.add(BluetoothProfile.HEADSET); 
} 

if (BluetoothUuid.containsAnyUuid(uuids, A2DP_PROFILE_UUIDS)) 
{ 
    profiles.add(BluetoothProfile.A2DP); 
} 

if (BluetoothUuid.containsAnyUuid(uuids, OPP_PROFILE_UUIDS)) 
{ 
    //OPP doesn't have any BluetoothProfile value 
} 

if (BluetoothUuid.containsAnyUuid(uuids, HID_PROFILE_UUIDS)) 
{ 
    //You will need system privileges in order to use this one 
    profiles.add(BluetoothProfile.INPUT_DEVICE); 
} 

if (BluetoothUuid.containsAnyUuid(uuids, PANU_PROFILE_UUIDS)) 
{ 
    profiles.add(BluetoothProfile.PAN); 
} 

第5步:拿到代理的配置文件,一個接一個:

for (int profile : profiles) 
{ 
    if (!adapter.getProfileProxy(context, listener, profile)) 
    { 
     //Do something 
    } 
} 

第6步:做你的聽衆的onServiceConnected方法檢索每個代理什麼。您可以使用relfection訪問connect方法。