开发者

Reflection issue of Android BluetoothService class

开发者 https://www.devze.com 2023-04-12 20:36 出处:网络
I want to call some methods like isEnabled(), getAddressFromObjectPath(), etc. of BluetoothService class, but this class is mark with @hide.

I want to call some methods like isEnabled(), getAddressFromObjectPath(), etc. of BluetoothService class, but this class is mark with @hide.

I know I have two possible ways to do what I want, one is remove the @hide, and the other is using reflection. I choose to use second one.

From the example of source code, I found that

    Method method = Class.forName("android.os.ServiceManager").getM开发者_开发问答ethod("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);

However, what it gets is the IBluetooth not BluetoothService although BluetoothService extends IBluetooth.Stub indeed.

So my questions are as follows:

(1) Could I get the BluetoothService class by reflection just like previous example code ? (2) If my first question is negative, I call getAddressFromObjectPath() directly by reflection method like following

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

what the object dose I need to fill in the invoke() method, BluetoothService ???

Any suggestion would be greatly appreciated !!!


After surveying on the internet, I got the answer. If I want to invoke a non-static method, I need to get the class and constructor first. Use the constructor to construct the instance and then I could invoke the non-static method by this instance. However, I could not do that on BluetoothService class because if I do the constructor again, it would cause a lot of problem ! I decide to modify the IBluetooth.aidl to add the methods I need because BluetoothService extends IBluetooth. If I could get the IBluetooth instance, I could call the methods I need. Maybe, this is not a good solution but I think it would work.

Thanks a lot.

0

精彩评论

暂无评论...
验证码 换一张
取 消