I have to develop an application for Android 1.6 (API 4), which should be able to use the OnAudioFocusChangeListener (available since Android 2.2 – API 8) in the phones with Android 2.2 or later.
Anyone can tell me how to instantiate a listener by reflection?
I have already managed to run static and also non-static methods by reflection, but I don’t know how to do with listeners.
This is the listener to reflect:
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
OnAudioFocusChangeListener audioListener = new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
// code to execute
}
};
public void getAudioFocus() {
audioManager.requestAudioFocus(audioListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
public void releaseAudioFocus() {
audioManager.abandonAudioFocus(audioListener);
}
This is a code example with methods I managed to run by reflection:
Class BluetoothAdapter = Class.forName("android.bluetooth.BluetoothAdapter");
Method methodGetDefaultAdapter = BluetoothAdapter.getMethod("getDefaultAdapter"); // static method from the BluetoothAdapter class returning a BluetoothAdapter object
Object bluetooth = methodGetDefaultAdapter.invoke(null);
Method methodGetState = bluetooth.getClass().getMethod("getState"); // non-static method executed from the BluetoothAdapter object (which I called "bluetooth") returning an int
int bluetoothState = (Integer) methodGetState.invoke(bluetooth);
In the end I solved it by using a Proxy class. Here is the code!
PROXY OnAudioFocusChangeListener class