Invocar un método privado (no publicado) en la API de Android

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: 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) {
    return connected;

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

preguntado el 16 de mayo de 11 a las 16:05

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? -

1 Respuestas

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.


Respondido 03 Feb 13, 16:02

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 API - user496854

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 relevant - user496854

Hi user496854, how did you get around the problem without calling private APIs? I am facing the same issue - George

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.