我必須爲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