2011-10-14 35 views
0

我想調用BluetoothService類的isEnabled(),getAddressFromObjectPath()等一些方法,但此類使用@hide標記。Android BluetoothService類的反射問題

我知道我有兩種可能的方式來做我想做的事情,一種是刪除@hide,另一種是使用反射。我選擇使用第二個。

從源代碼的例子,我發現

Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class); 
    IBinder b = (IBinder) method.invoke(null, "bluetooth"); 

    if (b == null) { 
     throw new RuntimeException("Bluetooth service not available"); 
    } 

    IBluetooth mBluetoothService = IBluetooth.Stub.asInterface(b); 

然而,它得到的是IBluetooth不BluetoothService雖然BluetoothService延伸IBluetooth.Stub確實如此。

所以我的問題如下:

(1)我能獲得通過,就像前面的示例代碼反射BluetoothService類? (2)如果我的第一個問題是否定的,我直接調用getAddressFromObjectPath()通過反射法等下列

Method method = Class.forName("android.server.BluetoothService").getMethod("getAddressFromObjectPath", String.class); 
    String b = (String) method.invoke(???, PATH); 

什麼對象劑量我需要填寫invoke()方法,BluetoothService ???

任何建議將不勝感激!

回答

1

經過互聯網調查後,我得到了答案。如果我想調用一個非靜態方法,我需要首先獲取類和構造函數。使用構造函數構造實例,然後可以通過此實例調用非靜態方法。 但是,我無法在BluetoothService類上做到這一點,因爲如果我再次構造函數,會導致很多問題! 我決定修改IBluetooth.aidl以添加我需要的方法,因爲BluetoothService擴展了IBluetooth。如果我能得到IBluetooth實例,我可以調用我需要的方法。也許,這不是一個好的解決方案,但我認爲它會起作用。

非常感謝。