Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to instantiate a listener by reflection in Android
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>This is the listener to reflect:</p> <pre><code>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); } </code></pre> <p>This is a code example with methods I managed to run by reflection:</p> <pre><code>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); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload