How Do I Intercept Button Presses On The Headset In Android?
Solution 1:
I recently developed an application which responded to the media button. I tested it in the Samsung Galaxy S II, and it worked.
First, in your AndroidManifest.xml
, inside the <application>
area, place the following:
<!-- Broadcast Receivers -->
<receiver android:name="net.work.box.controller.receivers.RemoteControlReceiver" >
<intent-filter android:priority="1000000000000000" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
Then, create a BroadcastReceiver
in a different file:
public class RemoteControlReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction()) {
KeyEvent event = (KeyEvent) intent .getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
context.sendBroadcast(new Intent(Intents.ACTION_PLAYER_PAUSE));
}
}
}
}
This is probably not the best solution out there (specially the hard coded android:priority
above). However, it tried a couple of other techniques and none of them seemed to work. So I have to resort to this one... I hope I helped.
Solution 2:
Thanks for contributing.
For all the others struggling here are the final conclusions :
After lots of blood tears I finally managed to realize that there are two types of broadcasts I can intercept: some like ACTION_HEADSET_PLUG
are required to be registered in the activities code.
Others like ACTION_MEDIA_BUTTON
are required to be registered in the Manifest file.
In this example to intercept both intents we require to do both.
Set it in the code and in the manifest file.
Solution 3:
if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
if (intent.hasExtra(Intent.EXTRA_KEY_EVENT)) {
String key = intent.getStringExtra(Intent.EXTRA_KEY_EVENT);
toast("Button "+key+" was pressed");
} else
toast("Some button was pressed");
}
This code return Toast "Button null was pressed"
Post a Comment for "How Do I Intercept Button Presses On The Headset In Android?"