2011-05-16 23 views
5

我需要檢查OS 2.0 - 2.3中的哪些BT耳機當前已連接(不僅配對)。這種功能在API版本11(其中引入了藍牙耳機類)之前不存在。但是之前的API中已經存在一個名爲BluetoothHeadset的類,但它不能公開訪問。以下是它的文檔:http://www.kiwidoc.com/java/l/x/android/android/9/p/android.bluetooth/c/BluetoothHeadset。所以,我試圖用反射來調用「isConnected」方法,但是我在反射時非常可怕,而且我得到一個錯誤java.lang.IllegalArgumentException: object is not an instance of the class在Android API中調用私有(未發佈)方法

我得到了使用BluetoothDevice.getBondedDevices()的配對設備列表,並且我嘗試在每個設備上使用isConnected()方法。這裏是代碼:

public boolean isBtDevConnected(BluetoothDevice btDev){ 
    boolean connected = false; 
    try { 
     Class<?> BTHeadset = Class.forName("android.bluetooth.BluetoothHeadset"); 
     Method isConnected = BTHeadset.getMethod("isConnected", new Class[] {BluetoothDevice.class}); 
       connected = isConnected.invoke(BTHeadset, new Object[] {btDev}); 
      } 
     } 
    } catch (Exception e) { 
     WriteToLog(e); 
    } 
    return connected; 
} 

我得到了調用該方法的行的異常,但我不知道我做錯了什麼。

+2

我想我意識到這個問題 - 我必須調用的invoke()的初始化BluetothHeadset對象,而不是BluetothHeadset類上。但是這給我帶來了另一個問題:我如何初始化BluetoothHeadset對象? – user496854 2011-05-16 17:57:04

回答

0

BluetoothHeadset是一個通過IPC控制藍牙耳機服務的代理對象。

使用getProfileProxy(Context,BluetoothProfile.ServiceListener,int)來獲取BluetoothHeadset代理對象。使用closeProfileProxy(int,BluetoothProfile)關閉服務連接。

Android一次只支持一個連接的藍牙耳機。每種方法都受到適當權限的保護。

來源:http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html

+0

正如我在原始問題中所述,這需要在較舊的API(2.2及更高版本)上工作,這就是爲什麼我需要訪問私有方法,而不是在API – user496854 2013-02-04 09:19:03

+0

此外,我解決了原本無需的問題調用這些API,所以在技術上來說,這個問題不再相關 – user496854 2013-02-04 09:20:14

+2

嗨user496854,你是如何在不調用私有API的情況下解決問題的?我面臨同樣的問題 – George 2013-12-10 13:17:55