I have been trying to achieve this. I have found this but they don't seem to help me:
http://android.amberfog.com/?p=415
Registering a headset button click with BroadcastReceiver in Android
https://issuetracker.google.com/issues/36910848
No matter what I try when I press the button on my head set the phone display the volume level control instead of being catch by my application and do something. Here is some of the code:
public class MediaButtonIntentReceiver extends BroadcastReceiver {
public MediaButtonIntentReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i("test1'", "test2");
String intentAction = intent.getAction();
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
return;
}
KeyEvent event = (KeyEvent) intent
.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
Log.i("test3'", "test4");
return;
}
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
// do something
Log.i("test5'", "test6");
}
abortBroadcast();
}
}
public class MainActivity extends Activity {
private static final String TAG = "BTAudioActivity";
private MediaPlayer mPlayer = null;
private AudioManager amanager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amanager = (AudioManager) getSystemService(AUDIO_SERVICE);
amanager.setBluetoothScoOn(true);
amanager.startBluetoothSco();
amanager.setMode(2);
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(new FileInputStream("/sdcard/sample.wav")
.getFD());
mPlayer.prepare();
mPlayer.setVolume(8,8);
mPlayer.start();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
MediaButtonIntentReceiver mMediaButtonReceiver = new MediaButtonIntentReceiver();
IntentFilter mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
mediaFilter.setPriority(1000);
registerReceiver(mMediaButtonReceiver, mediaFilter);
super.onResume();
}
@Override
public void onDestroy() {
mPlayer.stop();
amanager.setMode(2);
amanager.setBluetoothScoOn(false);
super.onDestroy();
}
}