2

I wanted to create a broadcastreceiver which listens for android.intent.action.MEDIA_BUTTON, and get the extra_key_event from that and act accordingly. Somehow the onreceive action is not performed.

In my Manifest:

receiver android:name="MediaButtonReceiver"
intent-filter
 action android:name="android.intent.action.MEDIA_BUTTON" 
intent-filter

receiver

In my broadcastreceiver:

public class MVCS extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
        /* handle media button intent here by reading contents */
        /* of EXTRA_KEY_EVENT to know which key was pressed    */

        KeyEvent ke = (KeyEvent)intent.getExtras().get(Intent.EXTRA_KEY_EVENT); 
        if (ke .getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
            Toast.makeText(context, "BUTTON PRESSED!", Toast.LENGTH_SHORT).show();  
        }
    }
}

However, nothing is displayed when i press the volume down key.

Any help would be much appreciated!

kevdliu
  • 1,709
  • 4
  • 29
  • 46

1 Answers1

0

You need to register your broadcast receiver in your Activity, with method registerReceiver(). As your code is not complete here, I can't tell you exactly how, but bear in mind that after instantiate your MVCS class, you should register like:

MyActivity.registerReceiver( myBroadcastReceiver, MediaButtonReceiver);

Better way of doing this is to register your receiver in OnStart() of your activity and unregister it in OnStop().

ruhalde
  • 3,521
  • 3
  • 24
  • 28
  • thanks for the help. Do broadcastreceivers run in the background continuously like a service even when my activity isnt running? – kevdliu Aug 26 '11 at 13:29
  • Broadcast receivers are not like services, nothing runs continously, is just a listener that you attach to some event, just that. It would execute ONLY when event is fired, and bear in mind that response is not that quick, sometimes it takes 300 or 400mS till your listener is fired. – ruhalde Aug 29 '11 at 18:23