我一直在努力实现这一目标。 我找到了这个,但他们似乎没有帮助我:
http://android.amberfog.com/?p=415
Registering a headset button click with BroadcastReceiver in Android
https://issuetracker.google.com/issues/36910848
无论我按下我头上的按钮时尝试了什么,手机都会显示音量控制而不是被我的应用程序捕获并执行某些操作。以下是一些代码:
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();
}
}