分享

转:android 线控按钮编程

 当年剩女图书馆 2014-10-21



 

 

为google到此的同学行个方便。

BTW:如果安装了子午播放器,可能receiver接收不到这个MEDIA_BUTTON的动作,具体的可以用DDMS连上去看。我也没分析清楚子午播放器是在哪里注册的。可能是在service里吧。

Introduction

Many Android devices come with the Music application used to play audio files stored on the device. Some devices ship with a wired headset that features transport control buttons, so users can for instance conveniently pause and restart music playback, directly from the headset.

But a user might use one application for music listening, and another for listening to podcasts, both of which should be controlled by the headset remote control.

If your media playback application creates a media playback service, just like Music, that responds to the media button events, how will the user know where those events are going to? Music, or your new application?

In this article, we’ll see how to handle this properly in Android 2.2. We’ll first see how to set up intents to receive “MEDIA_BUTTON”intents. We’ll then describe how your application can appropriately become the preferred media button responder in Android 2.2. Since this feature relies on a new API, we’ll revisit the use of reflection to prepare your app to take advantage of Android 2.2, without restricting it to API level 8 (Android 2.2).

An example of the handling of media button intents

In our AndroidManifest.xml for this package we declare the class RemoteControlReceiver to receive MEDIA_BUTTON intents:

 

 

Xml代码  收藏代码
  1. <receiver android:name="RemoteControlReceiver">  
  2.     <intent-filter>  
  3.          <action android:name="android.intent.action.MEDIA_BUTTON" />  
  4.     </intent-filter>  
  5. </receiver>  

 

 

Our class to handle those intents can look something like this:

 

 

Java代码  收藏代码
  1. public class RemoteControlReceiver extends BroadcastReceiver {  
  2.     @Override  
  3.     public void onReceive(Context context, Intent intent) {  
  4.         if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {  
  5.             /* handle media button intent here by reading contents */  
  6.             /* of EXTRA_KEY_EVENT to know which key was pressed    */  
  7.         }  
  8.     }  
  9. }  

 

 

 

In a media playback application, this is used to react to headset button presses when your activity doesn’t have the focus. For when it does, we override the Activity.onKeyDown()or onKeyUp() methods for the user interface to trap the headset button-related events.

However, this is problematic in the scenario we mentioned earlier. When the user presses “play”, what application should start playing? The Music application? The user’s preferred podcast application?

Becoming the “preferred” media button responder

In Android 2.2, we are introducing two new methods in android.media.AudioManager to declare your intention to become the “preferred” component to receive media button events: registerMediaButtonEventReceiver() and its counterpart,unregisterMediaButtonEventReceiver(). Once the registration call is placed, the designated component will exclusively receive theACTION_MEDIA_BUTTON intent just as in the example above.

In the activity below were are creating an instance of AudioManager with which we will register our component. We therefore create a ComponentName instance that references our intended media button event responder.

Java代码  收藏代码
  1. public class MyMediaPlaybackActivity extends Activity {  
  2.     private AudioManager mAudioManager;  
  3.     private ComponentName mRemoteControlResponder;  
  4.    
  5.     @Override  
  6.     public void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);  
  9.         mRemoteControlResponder = new ComponentName(getPackageName(),  
  10.                 RemoteControlReceiver.class.getName());  
  11. }  

 

The system handles the media button registration requests in a “last one wins” manner. This means we need to select where it makes sense for the user to make this request. In a media playback application, proper uses of the registration are for instance:

  • when the UI is displayed: the user is interacting with that application, so (s)he expects it to be the one that will respond to the remote control,
  • when content starts playing (e.g. content finished downloading, or another application caused your service to play content)

Registering is here performed for instance when our UI comes to the foreground:

Java代码  收藏代码
  1. @Override  
  2.    public void onResume() {  
  3.        super.onResume();  
  4.        mAudioManager.registerMediaButtonEventReceiver(  
  5.                mRemoteControlResponder);  
  6.    }  

 

If we had previously registered our receiver, registering it again will push it up the stack, and doesn’t cause any duplicate registration.

Additionally, it may make sense for your registered component not to be called when your service or application is destroyed (as illustrated below), or under conditions that are specific to your application. For instance, in an application that reads to the user her/his appointments of the day, it could unregister when it’s done speaking the calendar entries of the day.

Java代码  收藏代码
  1. @Override  
  2.    public void onDestroy() {  
  3.        super.onDestroy();  
  4.        mAudioManager.unregisterMediaButtonEventReceiver(  
  5.                mRemoteControlResponder);  
  6.    }  

 

After “unregistering”, the previous component that requested to receive the media button intents will once again receive them.

Preparing your code for Android 2.2 without restricting it to Android 2.2

While you may appreciate the benefit this new API offers to the users, you might not want to restrict your application to devices that support this feature. Let’s see how to enable your application to use the new media button mechanism when it runs on devices that support this feature.

First we declare in our Activity the two new methods we have used previously for the registration mechanism:

Java代码  收藏代码
  1. private static Method mRegisterMediaButtonEventReceiver;  
  2.     private static Method mUnregisterMediaButtonEventReceiver;  

 

We then add a method that will use reflection on the android.media.AudioManager class to find the two methods when the feature is supported:

Java代码  收藏代码
  1. private static void initializeRemoteControlRegistrationMethods() {  
  2.    try {  
  3.       if (mRegisterMediaButtonEventReceiver == null) {  
  4.          mRegisterMediaButtonEventReceiver = AudioManager.class.getMethod(  
  5.                "registerMediaButtonEventReceiver",  
  6.                new Class[] { ComponentName.class } );  
  7.       }  
  8.       if (mUnregisterMediaButtonEventReceiver == null) {  
  9.          mUnregisterMediaButtonEventReceiver = AudioManager.class.getMethod(  
  10.                "unregisterMediaButtonEventReceiver",  
  11.                new Class[] { ComponentName.class } );  
  12.       }  
  13.       /* success, this device will take advantage of better remote */  
  14.       /* control event handling                                    */  
  15.    } catch (NoSuchMethodException nsme) {  
  16.       /* failure, still using the legacy behavior, but this app    */  
  17.       /* is future-proof!                                          */  
  18.    }  
  19. }  

 

The method fields will need to be initialized when our Activity class is loaded:

Java代码  收藏代码
  1. static {  
  2.        initializeRemoteControlRegistrationMethods();  
  3.    }  

 

We’re almost done. Our code will be easier to read and maintain if we wrap the use of our methods initialized through reflection by the following. Note the actual method invocation on our AudioManager instance:

Java代码  收藏代码
  1. private void registerRemoteControl() {  
  2.         try {  
  3.             if (mRegisterMediaButtonEventReceiver == null) {  
  4.                 return;  
  5.             }  
  6.             mRegisterMediaButtonEventReceiver.invoke(mAudioManager,  
  7.                     mRemoteControlResponder);  
  8.         } catch (InvocationTargetException ite) {  
  9.             /* unpack original exception when possible */  
  10.             Throwable cause = ite.getCause();  
  11.             if (cause instanceof RuntimeException) {  
  12.                 throw (RuntimeException) cause;  
  13.             } else if (cause instanceof Error) {  
  14.                 throw (Error) cause;  
  15.             } else {  
  16.                 /* unexpected checked exception; wrap and re-throw */  
  17.                 throw new RuntimeException(ite);  
  18.             }  
  19.         } catch (IllegalAccessException ie) {  
  20.             Log.e(”MyApp”, "unexpected " + ie);  
  21.         }  
  22.     }  
  23.    
  24.     private void unregisterRemoteControl() {  
  25.         try {  
  26.             if (mUnregisterMediaButtonEventReceiver == null) {  
  27.                 return;  
  28.             }  
  29.             mUnregisterMediaButtonEventReceiver.invoke(mAudioManager,  
  30.                     mRemoteControlResponder);  
  31.         } catch (InvocationTargetException ite) {  
  32.             /* unpack original exception when possible */  
  33.             Throwable cause = ite.getCause();  
  34.             if (cause instanceof RuntimeException) {  
  35.                 throw (RuntimeException) cause;  
  36.             } else if (cause instanceof Error) {  
  37.                 throw (Error) cause;  
  38.             } else {  
  39.                 /* unexpected checked exception; wrap and re-throw */  
  40.                 throw new RuntimeException(ite);  
  41.             }  
  42.         } catch (IllegalAccessException ie) {  
  43.             System.err.println("unexpected " + ie);    
  44.         }  
  45.     }  

 

We are now ready to use our two new methods, registerRemoteControl()and unregisterRemoteControl() in a project that runs on devices supporting API level 1, while still taking advantage of the features found in devices running Android 2.2.

Original article written by Jean-Michel Trivi. You can find it here.
Comments and suggestions are welcome!!!..See you…

 


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多