0
I’m trying to record and capture events on the volume buttons of Android, so I can start and stop a service.
Researching I found several solutions using Broadcastreceiver, but it seems that none is working for my case.
What I’ve done so far is basically this (which isn’t working):
I created a Broadcastreceiver:
public class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("MediaButtonReceiver", "onReceive");
Toast.makeText(context, "Receiver!", Toast.LENGTH_LONG).show();
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
switch (event.getKeyCode()){
case KeyEvent.KEYCODE_VOLUME_DOWN:
Toast.makeText(context, "Volume down!", Toast.LENGTH_LONG).show();
break;
case KeyEvent.KEYCODE_VOLUME_UP:
Toast.makeText(context, "Volume up!", Toast.LENGTH_LONG).show();
break;
}
}
}
}
I registered the receiver in the AndroidManifest.xml
:
<receiver android:name=".MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
And registered on onCreate
of my Activity
main:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName rec = new ComponentName(this, MediaButtonReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(rec);
}
But it seems that something is missing, or something is incorrect, because the method onReceive
of MediaButtonReceiver
, is not being called by pressing the device’s volume buttons.
I’m running on Android 5.0.
I’ve seen it before that similar question that is unsolved.
- I accept solutions that require root access (rooted devices).
Fernando, it would have to be from a
Activity
your app or need to know even without your app being in use?– Wakim
@Wakim, it would have to be outside the App, it’s kind to start a service from anywhere, but the app has to be in the background.
– Fernando Leal