我必须为Android 1.6(API 4)开发一个应用程序,该应用程序应该能够在Android 2.2或更高版本的Android 2.2手机中使用OnAudioFocusChangeListener(可用于Android 2.2 - API 8)后来。如何通过Android中的反射来实例化侦听器
任何人都可以告诉我如何通过反射实例化侦听器? 我已经设法通过反射运行静态和非静态方法,但我不知道如何处理侦听器。
这是听众反映:
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);
}
这是一个有方法的代码示例,我设法通过反射来运行:
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);
这里是很好的例子http://blogs.oracle.com/poonam/entry/how_to_implement_an_interface – Ronnie