我需要檢查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;
}
我得到了調用該方法的行的異常,但我不知道我做錯了什麼。
我想我意識到這個問題 - 我必須調用的invoke()的初始化BluetothHeadset對象,而不是BluetothHeadset類上。但是這給我帶來了另一個問題:我如何初始化BluetoothHeadset對象? – user496854 2011-05-16 17:57:04