1 package com.example.android.musicplayer; 2 3 import android.content.ComponentName; 4 import android.media.AudioManager; 5 import android.util.Log; 6 7 import java.lang.reflect.InvocationTargetException; 8 import java.lang.reflect.Method; 9 10 /** 11 * Class that assists with handling new media button APIs available in API level 8. 12 */ 13 public class MediaButtonHelper { 14 // Backwards compatibility code (methods available as of API Level 8) 15 private static final String TAG = "MediaButtonHelper"; 16 17 static { 18 initializeStaticCompatMethods(); 19 } 20 21 static Method sMethodRegisterMediaButtonEventReceiver; 22 static Method sMethodUnregisterMediaButtonEventReceiver; 23 24 static void initializeStaticCompatMethods() { 25 try { 26 sMethodRegisterMediaButtonEventReceiver = AudioManager.class.getMethod( 27 "registerMediaButtonEventReceiver", 28 new Class[] { ComponentName.class }); 29 sMethodUnregisterMediaButtonEventReceiver = AudioManager.class.getMethod( 30 "unregisterMediaButtonEventReceiver", 31 new Class[] { ComponentName.class }); 32 } catch (NoSuchMethodException e) { 33 // Silently fail when running on an OS before API level 8. 34 } 35 } 36 37 public static void registerMediaButtonEventReceiverCompat(AudioManager audioManager, 38 ComponentName receiver) { 39 if (sMethodRegisterMediaButtonEventReceiver == null) 40 return; 41 42 try { 43 sMethodRegisterMediaButtonEventReceiver.invoke(audioManager, receiver); 44 } catch (InvocationTargetException e) { 45 // Unpack original exception when possible 46 Throwable cause = e.getCause(); 47 if (cause instanceof RuntimeException) { 48 throw (RuntimeException) cause; 49 } else if (cause instanceof Error) { 50 throw (Error) cause; 51 } else { 52 // Unexpected checked exception; wrap and re-throw 53 throw new RuntimeException(e); 54 } 55 } catch (IllegalAccessException e) { 56 Log.e(TAG, "IllegalAccessException invoking registerMediaButtonEventReceiver."); 57 e.printStackTrace(); 58 } 59 } 60 61 @SuppressWarnings("unused") 62 public static void unregisterMediaButtonEventReceiverCompat(AudioManager audioManager, 63 ComponentName receiver) { 64 if (sMethodUnregisterMediaButtonEventReceiver == null) 65 return; 66 67 try { 68 sMethodUnregisterMediaButtonEventReceiver.invoke(audioManager, receiver); 69 } catch (InvocationTargetException e) { 70 // Unpack original exception when possible 71 Throwable cause = e.getCause(); 72 if (cause instanceof RuntimeException) { 73 throw (RuntimeException) cause; 74 } else if (cause instanceof Error) { 75 throw (Error) cause; 76 } else { 77 // Unexpected checked exception; wrap and re-throw 78 throw new RuntimeException(e); 79 } 80 } catch (IllegalAccessException e) { 81 Log.e(TAG, "IllegalAccessException invoking unregisterMediaButtonEventReceiver."); 82 e.printStackTrace(); 83 } 84 } 85 } 86