1
我一直試圖實現這個爲2天,現在我似乎無法找到正確的答案。 我一直在尋找互聯網上的答案,並發現這一點,但他們似乎沒有幫助我:如何檢測藍牙耳機上的按鈕按
http://android.amberfog.com/?p=415
Android - registering a headset button click with BroadcastReceiver
http://code.google.com/p/android/issues/detail?id=4963
無論我怎麼努力,當我按下按鈕在我的頭上設置手機顯示音量控制,而不是被我的應用程序抓住並做一些事情。如果有人可以給我幾個提示,我會非常感謝。下面是一些代碼:
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();
}
}