Invoking a private (unpublished) method in Android API
Asked Answered
H

1

5

I need to check which BT headsets are currently connected (not just paired) in OS 2.0 - 2.3. Such functionality doesn't exist until API version 11, where a Bluetooth Headset class was introduced. But there already existed a class called BluetoothHeadset in prior APIs, but it wasn't publicly accessible. Here's the documentation for it: http://www.kiwidoc.com/java/l/x/android/android/9/p/android.bluetooth/c/BluetoothHeadset. So, I was trying to use reflection to invoke the "isConnected" method, but I'm pretty horrible at reflection, and I'm getting an error java.lang.IllegalArgumentException: object is not an instance of the class.

I got a list of paired devices using BluetoothDevice.getBondedDevices(), and I try to use the isConnected() method on each one. Here's the code:

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;
}

I get the exception on the line that invokes the method, but I'm not sure what I'm doing wrong.

Harty answered 16/5, 2011 at 16:31 Comment(1)
I think I realized the problem -- I have to call invoke() on an initialized BluetothHeadset object, not the BluetothHeadset class. But that brings me to another problem: how can I initialize a BluetoothHeadset object?Harty
S
0

BluetoothHeadset is a proxy object for controlling the Bluetooth Headset Service via IPC.

Use getProfileProxy(Context, BluetoothProfile.ServiceListener, int) to get the BluetoothHeadset proxy object. Use closeProfileProxy(int, BluetoothProfile) to close the service connection.

Android only supports one connected Bluetooth Headset at a time. Each method is protected with its appropriate permission.

source: http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html

Stricklan answered 3/2, 2013 at 12:47 Comment(3)
As I stated in the original question, this needs to work on older APIs (2.2 and up), that's why I needed to access theprivate methods not in the APIHarty
Also, I got around the problem that I was originally having without having to invoke those APIs, so technically speaking, this question is no longer relevantHarty
Hi user496854, how did you get around the problem without calling private APIs? I am facing the same issueAiguille

© 2022 - 2024 — McMap. All rights reserved.