2011-09-21 56 views
8

我必须为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); 
+1

这里是很好的例子http://blogs.oracle.com/poonam/entry/how_to_implement_an_interface – Ronnie

回答

6

最后我通过使用Proxy类来解决它。这是代码!

private AudioManager theAudioManager; 
private Object myOnAudioFocusChangeListener = null; 

private static final int AUDIOMANAGER_AUDIOFOCUS_GAIN = 1; 
private static final int AUDIOMANAGER_AUDIOFOCUS_LOSS = -1; 

theAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 

// instantiating the OnAudioFocusChangeListener by reflection (as it only exists from Android 2.2 onwards) 
// we use a Proxy class for implementing the listener 
public void setOnAudioFocusChangeListener() { 
    Log.i(this, "setOnAudioFocusChangeListener()"); 
    Class<?>[] innerClasses = theAudioManager.getClass().getDeclaredClasses(); 
    for (Class<?> interfaze : innerClasses) { 
     if (interfaze.getSimpleName().equalsIgnoreCase("OnAudioFocusChangeListener")) { 
      Class<?>[] classArray = new Class<?>[1]; 
      classArray[0] = interfaze; 
      myOnAudioFocusChangeListener = Proxy.newProxyInstance(interfaze.getClassLoader(), classArray, new ProxyOnAudioFocusChangeListener()); 
     } 
    } 
} 

// called by onResume 
public void getAudioFocus() { 
    if (myOnAudioFocusChangeListener != null) { 
     Log.i(this, "getAudioFocus()"); 
     try { 
      Method[] methods = theAudioManager.getClass().getDeclaredMethods(); 
      for (Method method : methods) { 
       if (method.getName().equalsIgnoreCase("requestAudioFocus")) { 
        method.invoke(theAudioManager, myOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AUDIOMANAGER_AUDIOFOCUS_GAIN); 
        Log.i(this, "requestAudioFocus"); 
       } 
      } 
     } catch (Exception e) { 
      Log.e(this, e.getMessage()); 
     } 
    } 
} 

// called by onPause 
public void releaseAudioFocus() { 
    if (myOnAudioFocusChangeListener != null) { 
     Log.i(this, "releaseAudioFocus()"); 
     try { 
      Method[] methods = theAudioManager.getClass().getDeclaredMethods(); 
      for (Method method : methods) { 
       if (method.getName().equalsIgnoreCase("abandonAudioFocus")) 
        method.invoke(theAudioManager, myOnAudioFocusChangeListener); 
      } 
     } catch (Exception e) { 
      Log.e(this, e.getMessage()); 
     } 
    } 
} 

PROXY OnAudioFocusChangeListener类

private class ProxyOnAudioFocusChangeListener implements InvocationHandler { 

    // implements the method onAudioFocusChange from the OnAudioFocusChangeListener 
    public void onAudioFocusChange(int focusChange) { 
     Log.e(this, "onAudioFocusChange() focusChange = " + focusChange); 
     if (focusChange == AUDIOMANAGER_AUDIOFOCUS_LOSS) { 
      Log.i(this, "AUDIOMANAGER_AUDIOFOCUS_LOSS"); 
      Message msg = mHandler.obtainMessage(ControllerHandler.SET_ON_PAUSE); 
      mHandler.sendMessage(msg); 
     } else if (focusChange == AUDIOMANAGER_AUDIOFOCUS_GAIN) { 
      Log.i(this, "AUDIOMANAGER_AUDIOFOCUS_GAIN"); 
      // no action is taken 
     } 
    } 

    // implements the method invoke from the InvocationHandler interface 
    // it intercepts the calls to the listener methods 
    // in this case it redirects the onAudioFocusChange listener method to the OnAudioFocusChange proxy method 
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
     Object result = null; 
     try { 
      if (args != null) { 
       if (method.getName().equals("onAudioFocusChange") && args[0] instanceof Integer) { 
        onAudioFocusChange((Integer) args[0]); 
       } 
      } 
     } catch (Exception e) { 
      throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); 
     } 
     return result; 
    } 
} 
1

恕我直言反射会使你的类的可读性。反射速度也比正常的场地或课程访问慢很多。

作为替代看到这里所描述的包装类方法:http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html

创建界面和它的两个实现,一个用于API 8+和其他的早期版本。在您的API8类中,您可以使用API​​ 8类,包括OnAudioFocusChangeListener。然后基于OS版本实例化版本,您可以通过Build.VERSION.SDK_INT进行检查。

+0

我不能完全肯定我可以使用的包装,如我需要将'OnAudioFocusChangeListener'对象作为参数传递给'AudioManager'对象的'requestAudioFocus'和'abandonAudioFocus'方法。我想如果传递OnAudioFocusChangeListener包装代替它不起作用。 –

+0

您可以将它作为内部包装类中的内部类。这会工作。 –

+0

我也会给反射一个错误 - 这是代码异味 - 特别是当有更好的方法来解决它时。使用包装方法 - 更好。 – Martyn

相关问题