I want to use the HEADSETHOOK button (keycode 79) on my Samsung earphones but cannot get it to work. I am, essentially, following the answer given in this SO question. My phone is a Samsung Galaxy S7 running Android v8.
The relevant part of my manifest is:
<receiver android:name=".MainActivity$HeadsetBtnReceiver" android:enabled="true" >
<intent-filter android:priority="10000000" >
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
My Activity (which includes the BroadcastReceiver) is:
public class MainActivity extends AppCompatActivity {
static AudioManager mAudioManager;
static ComponentName mReceiverComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mReceiverComponent = new ComponentName(this, HeadsetBtnReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mReceiverComponent);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onBackPressed() {
Log.e("Udp", "Backpress MainActivity");
finish();
}
@Override
public void onDestroy() {
Log.e("UDP svc", "Destroying MainActivity");
mAudioManager.unregisterMediaButtonEventReceiver(mReceiverComponent);
finish();
super.onDestroy();
}
public static class HeadsetBtnReceiver extends BroadcastReceiver {
// Constructor is mandatory
public HeadsetBtnReceiver()
{
super ();
}
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
Log.e("Udp svc", intentAction.toString() + " happened");
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
Log.e("Udp svc", "no media button information");
return;
}
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
Log.e("Udp svc", "no keypress");
return;
}
KeyEvent key = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
Log.e("UDP svc", "KeyEvent : ");
if(key.getAction() == KeyEvent.ACTION_UP) {
int keycode = key.getKeyCode();
if(keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
Log.e("Udp svc", "Next Pressed");
} else if(keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
Log.e("Udp svc", "Previous pressed");
} else if(keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
Log.e("Udp svc", "Head Set Hook pressed");
}
}
}
}
}
When I run the app I get no Logcat messages, all that happens is that I get the default actions for both the volume buttons and the other, single, button.
I believe that the BroadcastReceiver has been deprecated in favour of MediaSession but as far as I can make out that only recognises the volume buttons.
What am I doing wrong?