Search code examples
androidservicereceiver

How to detect key events in service and broadcast receiver


How can I get key events when a user presses various buttons in a service or broadcast receiver? I'm specifically interested in knowing when the user presses a volume button so that I can trigger something else in the background, like a voice recorder.

Unfortunately, my internet searches haven't produced any results.


Solution

  • Something like the following should work:
    From official documentation:

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"...>
        //code, like activities, etc
    
        <receiver android:name="com.example.test.VolumeBroadcast" >
            <intent-filter>
               <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
    </application>
    

    Example of a receiver:

      public class VolumeBroadcast extends BroadcastReceiver{
    
          public void onReceive(Context context, Intent intent) {
               //check the intent something like:
               if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
                  KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                  if (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()) {
                     // Handle key press.
                  }
               }
          }
      }
    

    The way you register is like that:

     AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
    // Start listening for button presses
    am.registerMediaButtonEventReceiver(RemoteControlReceiver); 
    // Stop listening for button presses
    am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
    

    Page below:
    Audio Playback