2011-09-21 14 views
8

Muszę opracować aplikację dla Androida 1.6 (API 4), która powinna być w stanie używać OnAudioFocusChangeListener (dostępnej od wersji 2.2 - API 8) w telefonach z Androidem 2.2 lub później.jak utworzyć instancję odszukującą poprzez odbicie w Androidzie

Ktoś może mi powiedzieć, jak utworzyć słuchacza przez odbicie? Udało mi się już uruchomić metody statyczne i niestatyczne za pomocą refleksji, ale nie wiem, jak to zrobić ze słuchaczami.

To słuchacza do refleksji:

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); 
} 

To jest przykładowy kod z metod udało mi się uruchomić poprzez odbicie:

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

Oto dobry przykład http://blogs.oracle.com/poonam/entry/how_to_implement_an_interface – Ronnie

Odpowiedz

6

W końcu rozwiązałem go, używając klasy Proxy. Oto kod!

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 klasa

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

IMHO odbicie sprawi, że zajęcia mniej czytelny. Również odbicie jest nieco wolniejsze niż normalne pole lub dostęp do klasy.

Jako alternatywę zobaczyć podejście klasy otoki opisane tutaj: http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html

Tworzenie interfejsu i dwie implementacje niego, jeden dla API 8+ i drugi dla wcześniejszych wersji. W swojej klasie API8 możesz używać klas API 8, w tym OnAudioFocusChangeListener. Następnie stwórz wersję na podstawie wersji systemu operacyjnego, którą możesz sprawdzić przez Build.VERSION.SDK_INT.

+0

nie jestem całkowicie pewien, że mogę używać opakowania, jak Muszę przekazać obiekt 'OnAudioFocusChangeListener' jako argument do metod' requestAudioFocus' i 'abandonAudioFocus' obiektu' AudioManager'. Przypuszczam, że to nie działa, jeśli zamiast tego otoczy się opakowanie OnAudioFocusChangeListener. –

+0

Możesz mieć go jako wewnętrzną klasę wewnątrz klasy opakowania. To by działało. –

+0

Dałbym też refleksji tęsknię - to jest zapach kodu - zwłaszcza, gdy jest lepszy sposób na jej rozwiązanie. Użyj metody otoki - o wiele ładniej. – Martyn

Powiązane problemy